【问题标题】:Set model from action and reload template in ember js从动作设置模型并在ember js中重新加载模板
【发布时间】:2014-05-13 10:56:49
【问题描述】:

我已经从另一个动作控制器重定向到一个控制器。 this.get('controllers.searchResult').send('searchDoc', query);

这里我使用AJAX请求获取数组对象

App.SearchResultController = Ember.ArrayController.extend({

serverURL: 'someURL',

actions: {
    searchDoc: function(query) {

        $.ajax({
            type: "GET",
            url: serverURL + request,
            data : 'q=' + query,
            dataType : "JSON",
            context : this, // to increase the scope of 
            statusCode : {
                200 : function(response) {

                    var docs = [];
                    response.docs.forEach(function(doc) {
                        docs.push(App.Doc.create(doc));
                    });

                    // do something here so that
                    // docs get save in the model
                    // and result page get reload
                },
                400 : function() {
                    console.log('status 400 something went wrong');
                }
            }
        });
    }
}
});

我是 Ember JS 的新手。我愿意在模型中存储/保存/添加这个docs 对象并重新加载我的路线searchResult

【问题讨论】:

    标签: javascript jquery ember.js jsonp


    【解决方案1】:

    您应该保留对控制器的引用,并在返回结果时使用它来设置content

    例子:

    App.SearchResultController = Ember.ArrayController.extend({
    serverURL: 'someURL',
    
    actions: {
        searchDoc: function(query) {
            var self = this; // keep a reference to the controller
    
            $.ajax({
                type: "GET",
                url: serverURL + request,
                data : 'q=' + query,
                dataType : "JSON",
                statusCode : {
                    200 : function(response) {
    
                        var docs = Ember.A();
                        response.docs.forEach(function(doc) {
                            docs.pushObject(App.Doc.create(doc));
                        });
    
                        self.set('content', docs); // use the controller reference to set the content
                    },
                    400 : function() {
                        console.log('status 400 something went wrong');
                    }
                }
            });
        }
    }
    });
    

    我还在示例中添加了 Ember 数组的用法。 设置content 应该会触发您的视图更新。

    您可以使用以下方法转换到 searchResult:

    this.get('controllers.searchResult').send('searchDoc', query);
    this.transitionToRoute('searchResult');
    

    【讨论】:

    • 感谢您的回答。我已经在使用它,但没有使用 self。尽管如此,我必须使用self.set('content', response.docs); 代替上述命令才能使其工作。
    猜你喜欢
    • 2018-02-26
    • 1970-01-01
    • 1970-01-01
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-19
    • 2014-06-10
    相关资源
    最近更新 更多