Ember.js观察者在异步更新后没有触发

时间:2013-10-30 15:22:59

标签: javascript jquery asynchronous ember.js

App.BaseRoute = App.AuthenticatedRoute.extend({
    setupController: function(controller, model){
        var cuser = this.controllerFor('application').get('currentUser');
        controller.set('model',model);
        this.controllerFor('base').set("currTags",App.User.getUserTags(cuser._id.$oid));
    }
});

App.IndexRoute = App.BaseRoute.extend({
    model: function(params) {
        return {"adsf" :"blah"};
    },  
    setupController: function(controller, model){
        this._super(controller,model);
        this.controllerFor('posts').set('model',model);
    }
});

App.User.reopenClass({
    getUserTags: function(userid) {
        var currTags = []; //create an empty object
        currTags.set('isLoaded',false);
        console.log(currTags);
        $.ajax({
            type: "GET",
            url : "/user/"+userid+"/default_tags",
            dataType: "application/json",
            //contentType : "application/json"
        }).then(this,function(data){
            data = JSON.parse(data.responseText);

            data.models.tags.forEach(function(tag){
                var model = App.Tag.create(tag); 
                model.value = model.name;
                currTags.addObject(model); //fill your array step by step

            });
            console.log(currTags);
            currTags.set("isLoaded", true);

        });
        console.log(currTags);
        return currTags;
    }
});

App.IndexController = Ember.ArrayController.extend({
    needs: ['application','base' ,'posts'],
    currentUser: Ember.computed.alias("controllers.application.currentUser"),
    posts : Ember.computed.alias("controllers.posts"),
    currTags: Ember.computed.alias("controllers.base.currTags"),
    actions: {
        initCurrentTags: function() {

        }.observes('currTags.isLoaded')
    }
});

我更新currTags但initCurrentTags永远不会被命中。

1 个答案:

答案 0 :(得分:2)

计算属性,并且观察不应该存在于动作哈希中。

不正确

App.IndexController = Ember.ArrayController.extend({
    needs: ['application','base' ,'posts'],
    currentUser: Ember.computed.alias("controllers.application.currentUser"),
    posts : Ember.computed.alias("controllers.posts"),
    currTags: Ember.computed.alias("controllers.base.currTags"),
    actions: {
        initCurrentTags: function() {

        }.observes('currTags.isLoaded')
    }
});

正确

App.IndexController = Ember.ArrayController.extend({
    needs: ['application','base' ,'posts'],
    currentUser: Ember.computed.alias("controllers.application.currentUser"),
    posts : Ember.computed.alias("controllers.posts"),
    currTags: Ember.computed.alias("controllers.base.currTags"),
    initCurrentTags: function() {

    }.observes('currTags.isLoaded')

    actions: {

    }
});