2015年7月26日 星期日

ember filterExample

 **html**
   <div class="col-sm-12">
            {{input type="text" value=search placeholder="filter 'phone' field...."}}
        </div>

  <ul class="list-group">
            {{#each filterResult as |phone| }} {{#link-to 'phones.viewPhone' phone.objectId}}
            <li {{ bindAttr class=":list-group-item" }}>
                {{phone.phone}}
            </li>
            {{/link-to}} {{/each}}

            <br>
        </ul>

  **html**

App.PhonesController = Ember.Controller.extend({

    search: '',
    filterResult: function() {
        var model = this.get('model');
        var search = this.get('search');
        if (Ember.isEmpty(search)) {

            return model;
        }
        Ember.Logger.log('PhonesController filterResult search:' + this.get('search'));
        var result = model.filter(function(item, index, self) {
            //Ember.Logger.log('PhonesController model.filter item:'+JSON.stringify(item));
            //item:{"first":"544","last":"121","phone":"0938","objectId":"D61qwtLr6g","createdAt":"2015-07-25T13:18:33.600Z","updatedAt":"2015-07-25T13:18:33.600Z"}"
            if (item['phone'].indexOf(search) >= 0) {
                return true;
            }
        });
        return result;

//model is route's model not local var!!
//if not in property then model change ,the filterResult can't trigger!!!
    }.property('search','model'),
    init: function() {
        this._super();
        Ember.Logger.log('PhonesController now init...');
    },
    actions: {
        parseList: function() {
            console.log("PhonesController send('parseListAction')");
            return this.send('parseListAction');
        },
        filterResult: function() {
            return this.filterResult();
        },
        addClick: function() {
            this.transitionToRoute('phones.add');
        }

    }




});

-raphael-js

http://code.tutsplus.com/tutorials/an-introduction-to-the-raphael-js-library--net-7186

emberjs object 繼承

http://xbingoz.com/emberguides/7.php#top

App.ParseTool = Ember.Object.extend({
   init:function  () {
            Parse.initialize("57ky0yYlGjtL93qWuMG2rYNt1HMBlO0CLLIhKmgb", "ISFeeGTcJ8fsvTX9NOrxRkj6MhnzPkNWOgqnLUsK");
            },getQueryOfPhone:function  () {
                var Phone = Parse.Object.extend("Phone");
                var query = new Parse.Query(Phone);
                return  query;
            },log:function (str) {
        Ember.Logger.log('ParseToolLogger:'+str);
    }

});
App.PhonesHttp = App.ParseTool.extend({
    logme:function (str) {
        this.log(str);
    }
  
});

DI in emberjs

if you are using cli you must use "ember generate 'service' and 'initializer' "


service as a object
 initializer:
import Phonehttp from '../services/phone-http';


export default {
  name: 'application',
  initialize: function initialize( container, application ) {
    application.register( 'phone-http:services', Phonehttp, { singleton: true } );
    application.inject( 'route:index', 'Phonehttp', 'phone-http:services' );
    }
};


service:
import Ember from 'ember';

export default Ember.Service.extend({
    log(){
        console.log('by Service log');
    }
});

route/index
import Ember from 'ember';

export default Ember.Route.extend({
    beforeModel:function  () {
        this.Phonehttp.log();
        this.transitionTo('posts');
    }
});

 


http://emberjs.com/api/classes/Ember.Application.html#method_inject
 https://github.com/kelonye/ember-user/blob/master/lib/index.js
http://balinterdi.com/2014/05/01/dependency-injection-in-ember-dot-js.html
http://wrktg.com/articles/understanding-application-register-and-inject-methods/
http://guides.emberjs.com/v1.13.0/understanding-ember/dependency-injection-and-service-lookup/




ex://register
 container.register('alertTool:object', App.AlertTool, {
            singleton: true
        });

   container.register('phonesHttp:object', App.PhonesHttp, {
            singleton: true
        });   
       
   container.register('controller:phones', App.PhonesController, {
            singleton: true
        });     
//PhonesController
  application.inject('route:phones', 'PhonesController', 'controller:phones');

        //alertTool
        application.inject('route:phones', 'AlertTool', 'alertTool:object');
        application.inject('controller:phones.viewPhone', 'AlertTool', 'alertTool:object');
        //phonesHttp
        application.inject('route:phones', 'PhonesHttp', 'phonesHttp:object');
        application.inject('controller:phones.viewPhone', 'PhonesHttp', 'phonesHttp:object');

    }
njections can be made onto all of Ember's major framework classes including components, controllers, routes, and the router.

 
App = Ember.Application.create();

App.Router.map(function() {
    this.resource('about');
    this.resource('calc');
    this.resource('todo');
    this.route('phones', function() {
        this.route('viewPhone', {
            path: "/viewPhone/:pathid"
        });
    });



});

Ember.Application.initializer({

//must has name field 'name'
    name:'init',

  initialize: function(container, application) {
    container.register('tool:object', App.Tool, { singleton: true });
    application.inject('route:phones', 'Tool', 'tool:object');
  }
});


App.Tool = Ember.Object.extend({
    showAlertDivId:'',
            fail: "<div class='alert alert-danger'> fail </div>",
            sus: "<div class='alert alert-success'> sus </div>",
            removeAlert: function() {
                var id=this.get('showAlertDivId');
                setTimeout(function  () {
                 $('#'+id).empty();
                }, 2000);
            },
            susAlert: function() {
                $('#'+this.showAlertDivId).append(this.sus);
                this.removeAlert();
            },failAlert:function(){
                  $('#'+this.showAlertDivId).append(this.fail);
                this.removeAlert();
            },setShowAlertDivId:function  (name) {
               return  this.set('showAlertDivId',name);
            },getQueryOfPhone:function  () {
                var Phone = Parse.Object.extend("Phone");
                var query = new Parse.Query(Phone);
                return  query;
            }
});
App.PhonesRoute = Ember.Route.extend({
    init: function() {
        this._super();
        Ember.Logger.log('PhonesRoute now init...');
    },
    model: function() {
        //this.Logger.log('example');
        return this.parseList();
    },
    parseList: function() {
        var tool=this.Tool;
        Ember.Logger.log('PhonesRoute parseList Ember.RSVP.Promise');
        return new Ember.RSVP.Promise(function(resolve, reject) {
            var resolve1 = resolve;
            var reject2 = reject;
           
            //var Phone = Parse.Object.extend("Phone");
            //var query = new Parse.Query(Phone);
            tool.setShowAlertDivId('status');
            var query=tool.getQueryOfPhone();
            query.find({
                success: function(results) {
                    tool.susAlert();
                    //con.transitionTo('phones', results);
                    var strjson = JSON.stringify(results); //array to string
                    //Ember.Logger.log('parseList strjson:' + JSON.stringify(strjson));
                    var jsonobj = JSON.parse(strjson); //string to object
                    //Ember.Logger.log('PhonesRoute parseList jsonobj:' + JSON.stringify(jsonobj));
                    resolve1(jsonobj);
                },
                error: function(model, error) {
                    Ember.Logger.log('PhonesRoute parseList error:' + JSON.stringify(error));
                    tool.failAlert();
                    this.nowList = error;
                    reject2(error);
                }
            });
        });
    },

    actions: {
         loading: function(transition, originRoute) {
         console.log("PhonesRoute loading");
        },
        parseListAction: function() {
            console.log("PhonesRoute this.parseList()");
            return this.parseList();
        },invalidateModel: function() {      Ember.Logger.log('PhonesRoute is now refreshing...');      this.refresh();    }
    }
});

2015年7月25日 星期六

javascript JSON.parse

parse.com 傳回的array陣列

{"results":[{"avatar":"中文名稱","createdAt":"2015-07-22T12:58:04.722Z","first":"中文名稱","last":"中文名稱","name":"中文名稱","objectId":"Xu3nMRCjO0","phone":"1212","updatedAt":"2015-07-22T12:58:04.722Z"},{"avatar":"12","createdAt":"2015-07-25T04:23:37.618Z","first":"1231","last":"51","name":"12","objectId":"FjtkSEIM93","phone":"963","updatedAt":"2015-07-25T04:23:49.516Z"}]}

 要轉為物件才可以給ember使用

var strjson = JSON.stringify (results);//array to string
                    Ember.Logger.log('parseList strjson:'+JSON.stringify(strjson));
                    var jsonobj = JSON.parse(strjson);//string to object
                    Ember.Logger.log('parseList res:'+JSON.stringify(jsonobj));

transitionToRoute the same route problem


http://stackoverflow.com/questions/18624601/correct-way-to-transitiontoroute/18642910

A route with a dynamic segment will only have its model hook called when it is entered via the URL. If the route is entered through a transition (e.g. when using the link-to Handlebars helper), then a model context is already provided and the hook is not executed. Routes without dynamic segments will always execute the model hook.

sol:
http://guides.emberjs.com/v1.10.0/routing/specifying-a-routes-model/


App = Ember.Application.create();

App.Router.map(function() {
    this.resource('about');
    this.resource('calc');
    this.resource('todo');
    this.resource('phones', function() {
        this.route('viewPhone', {
            path: "/viewPhone/:userid"
        });
    });


});

var varphones = [{
    objectId: 0,
    first: 'Ryan',
    last: 'Florence',
    avatar: 'https://si0.twimg.com/profile_images/3123276865/5c069e64eb7f8e971d36a4540ed7cab2.jpeg',
    phone: '0938535359'

}, {
    objectId: 1,
    first: 'Tom',
    last: 'Dale',
    avatar: 'https://si0.twimg.com/profile_images/1317834118/avatar.png',
    phone: '0938535349'
}, {
    objectId: 2,
    first: 'Yehuda',
    last: 'Katz',
    avatar: 'https://si0.twimg.com/profile_images/3250074047/46d910af94e25187832cb4a3bc84b2b5.jpeg',
    phone: '0938535459'
}];
App.PhonesRoute = Ember.Route.extend({
    model: function() {
        return varphones;
    },
  actions: {
    invalidateModel: function() {
      Ember.Logger.log('Route is now refreshing...');
      this.refresh();
    }
  }

});

App.PhonesViewPhoneRoute = Ember.Route.extend({

    model: function(params) {
        console.log(params);
        return varphones[params.objectId];
    }

  
});

App.PhonesController = Ember.Controller.extend({
    name: '',
    phone: '',
    search: '',

    init: function() {
        this._super();
        Parse.initialize("57ky0yYlGjtL93qWuMG2rYNt1HMBlO0CLLIhKmgb", "ISFeeGTcJ8fsvTX9NOrxRkj6MhnzPkNWOgqnLUsK");
        var tool = Object.create(Tool);
        tool.showAlertDivId = 'status';
    },
    actions: {
        parseSave: function() {

            if (this.phone.length <= 0) {
                tool.failAlert();
                return;
            }
            if (this.name.length <= 0) {
                tool.failAlert();
                return;
            }
            var Phone = Parse.Object.extend("Phone");
            var phone = new Phone();
            phone.set('name', this.get('name'));
            phone.set('phone', this.get('phone'));
            phone.set('first', this.get('name'));
            phone.set('last', this.get('name'));
            phone.set('avatar', this.get('name'));


            phone.save(null, {

                success: function(object) {

                    tool.susAlert();
                },
                error: function(model, error) {

                    tool.failAlert();
                }

            });
        },
        parseList: function() {
            var tool = Object.create(Tool);
            tool.showAlertDivId = 'status';
            var Phone = Parse.Object.extend("Phone");
            var query = new Parse.Query(Phone);
            var con=this;
             query.find({
                success: function(results) {
                    varphones=results;
                    console.log("varphones:"+JSON.stringify(varphones));
                    tool.susAlert();
                    Ember.Logger.log('Controller requesting route to refresh...');
                    con.send('invalidateModel');//"Controller requesting route to refresh..."

                },
                error: function(model, error) {

                    tool.failAlert();
                    this.nowList = error;
                }
            }).then(function  () {
             
            });
        }


    }




});

Learning Ember

https://www.emberscreencasts.com/posts?free=true


http://www.smashingmagazine.com/2013/11/an-in-depth-introduction-to-ember-js/

2015年7月18日 星期六

difference fo '.resoure' and '.route' in route

import Ember from 'ember';


var Router = Ember.Router.extend({

});

Router.map(function() {
    this.resource('posts', function() {
        this.route('new');
        this.route('edit');
        this.route('post',{'path':'/:postId'});
    });
});
export default Router;
 
ember will read template from posts/new

if you use resource will read template from new

rested and dynamic route example

http://guides.emberjs.com/v1.10.0/routing/defining-your-routes/

import Ember from 'ember';


var Router = Ember.Router.extend({

});

Router.map(function() {
    this.resource('posts', function() {
        this.resource('new');
        this.resource('post',{'path':'/:postId'});
    });
});
export default Router;

ember route index trap

if you use index

\templates\posts\index
there will only load index

but is you set to
\templates\posts
you can use
\templates\posts\new
\templates\posts\other

ui-icon addon

https://www.npmjs.com/package/ui-icon





ember install ui-icon



bower install --save fontawesome

bower install --save
https://github.com/daneden/animate.css.git
http://daneden.github.io/animate.css
\components\list-button.js
import Ember from 'ember';
//fa-pencil
export default Ember.Component.extend({
    righttext: 'comright',
    faIconName:'pencil',
    actions: {
        comfaCLick: function() {
            console.log('comfaCLick');
        },
        select: function(post) {
            this.sendAction('selectitem',post);//send to parent's controller
        }
    }
}); 

\templates\components\list-button.hbs
<ul class="list-group posts">
        {{#each listdata key="@index" as |post|}}
        <li class="clearfix list-group-item" {{action 'select' post}} >
       
            <div class="itemleft col-xs-7">
                <span> {{post.title}}</span>
            </div>
            <div class="itemright col-xs-3">
                <span  {{action 'comfaCLick' post}}></span>
            {{ui-icon icon= faIconName }}
            </div>
           
           
        </li>
        {{/each}}
    </ul>.

2015年7月12日 星期日

list-group-items 疊再一起

http://stackoverflow.com/questions/24285260/bootstrap-css-height-of-list-group-item

Since you are using Bootstrap you could add the class="clearfix" to HTML for the list-group-items

2015年7月2日 星期四

print a list and bindclass

http://jsbin.com/aconeh/3/edit?html,js,output
http://ember101.com/videos/003-displaying-a-list-of-data


App = Ember.Application.create();

App.Router.map(function() {
    this.resource('about');
    this.resource('calc');
    this.resource('todo');
    this.resource('phones');
});

var users = [
  {
    id: 1,
    first: 'Ryan',
    last: 'Florence',
    avatar: 'https://si0.twimg.com/profile_images/3123276865/5c069e64eb7f8e971d36a4540ed7cab2.jpeg'
    ,phone:'0938535359'

  },
  {
    id: 2,
    first: 'Tom',
    last: 'Dale',
    avatar: 'https://si0.twimg.com/profile_images/1317834118/avatar.png'
    ,phone:'0938535349'
  },
  {
    id: 3,
    first: 'Yehuda',
    last: 'Katz',
    avatar: 'https://si0.twimg.com/profile_images/3250074047/46d910af94e25187832cb4a3bc84b2b5.jpeg'
    ,phone:'0938535459'
  }
];
App.PhonesRoute = Ember.Route.extend({
//modelis a reserved word can't write to smodel or xname or yname..etc
    model: function() {
         console.log(users);
    return users;
    }
});


App.PhonesController = Ember.Controller.extend({

    search: '',
    actions: {
        query: function function_name() {
            var str = this.get('search');
            console.log(str);
        }
    }
});



index.html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Ember Starter Kit</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="css/normalize.css">
    <link rel="stylesheet" href="css/app.css">
    <link rel="stylesheet" href="css/style.css">
</head>

<body>

    <script src="js/libs/jquery-1.10.2.js"></script>

    <script src="js/libs/ember.min.js"></script>
    <script src="js/libs/ember-template-compiler.js"></script>
    <script src="js/libs/ember.prod.js"></script>
    <script src="js/libs/handlebars-v3.0.3.js"></script>
    <script src="js/libs/bootstrap.min.js"></script>
    <script type="text/javascript" src="ember-data.min.js"></script>
    <script type="text/javascript" src="state.js"></script>
    <script type="text/javascript" src="state_manager.js"></script>




    <script src="js/app.js"></script>
    <!-- to activate the test runner, add the "?test" query string parameter -->
    <script src="tests/runner.js"></script>


    <script type="text/x-handlebars" data-template-name="phones">
        {{input type="text"value=search placeholder="text to query..." action="query"}}
        <br>
        <ul class="list-group">
            <li class="list-group-item">1</li>
            {{#each  phone in model}}
//sould be    ":list-group-item" not "list-group-item"
               <li {{ bindAttr class=":list-group-item" }} >
                 {{phone.first}} , {{phone.last}}
                 </li>
            {{/each}}
        </ul>
    </script>



    <script type="text/x-handlebars">
        <div id='top'>
            <nav class="navbar navbar-inverse">
                <div class="container-fluid">
                    <div class="navbar-header">
                        <a class="navbar-brand" href="#">I am keith</a>
                    </div>
                    <div>
                        <ul class="nav navbar-nav">
                            <li class="active"><a href="#">Home</a></li>
                            <li><a href="#/about">about</a></li>
                            <li><a href="#/calc">calc</a></li>
                            <li><a href="#/todo">todo</a></li>
                            <li><a href="#/phones">phones</a></li>
                        </ul>
                    </div>
                </div>
            </nav>
        </div>
        <div id='contents'>
            {{outlet}}
        </div>
        <div id='footer'>
            Copyright © 2015 LFO keith. All rights reserved
        </div>




    </script>
    <script type="text/x-handlebars" data-template-name="about">
        <div class="jumbotron">
            <div class="container">
                <h1>My  ember website!</h1>
                <p>This my pratices</p>
            </div>
        </div>
    </script>
    <script type="text/x-handlebars" data-template-name="calc">
        this is calc
    </script>

    <script type="text/x-handlebars" data-template-name="todo">
        this is todo
    </script>
</body>

</html>

2015年7月1日 星期三

angular js muti modules



var alert=angular.module('alert',['ui.bootstrap']).controller('AlertDemoCtrl', function ($scope) {
  $scope.alerts = [
    { type: 'danger', msg: 'Oh snap! Change a few things up and try submitting again.' },
    { type: 'success', msg: 'Well done! You successfully read this important alert message.' }
  ];

  $scope.addAlert = function() {
    $scope.alerts.push({msg: 'Another alert!'});
  };

  $scope.closeAlert = function(index) {
    $scope.alerts.splice(index, 1);
  };
});

//just add in your main app called phonecatApp 
var phonecatApp = angular.module('phonecatApp', ['alert']);

phonecatApp.controller('PhoneListCtrl', function ($scope) {
  $scope.phones = [
    {'name': 'Nexus S',
     'snippet': 'Fast just got faster with Nexus S.'},
    {'name': 'Motorola XOOM™ with Wi-Fi',
     'snippet': 'The Next, Next Generation tablet.'},
    {'name': 'MOTOROLA XOOM™',
     'snippet': 'The Next, Next Generation tablet.'}
  ];
});

Git 常用命令备忘

http://www.lovelucy.info/git-command-cheatsheet.html#more-2109

anglarjs

angular-ui.
https://angular-ui.github.io/bootstrap/