2015年7月26日 星期日

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();    }
    }
});

沒有留言:

張貼留言