【问题标题】:Pass attributes or options to backbone model将属性或选项传递给主干模型
【发布时间】:2014-07-19 10:50:42
【问题描述】:

我没有在模型中获得任何属性或选项。我需要向它传递一个路由号才能构建一个 url。有人看到我缺少什么或我应该怎么做吗?我尝试在模型上设置我想要的属性,但是当我尝试抓取它时它不在模型中。

查看

define([
'text!html/tplDirection.html',
'models/direction',
'core'
], function (template, Direction) {

return Backbone.View.extend({
    el: '',
    template: _.template(template),
    initialize: function (options) {
        this.model = new Direction();       
        this.model.set({rtnm: options.routeNumber});
        console.log(this.model);
    },
    setup: function (routeNumber) {
        var self = this;
        // self.model.set({rtnm: routeNumber});
        $.when(self.model.fetch())
            .done(function () {
                console.log(self.model.toJSON());               
                self.render();
            })
            .fail(function (response) {
                console.log(response);
                console.log('request for data has failed');
            });         
    },

    render: function () {
    var data = {
        model: this.model.toJSON()
    };
        this.$el.html(_.template(template, data));
    },

型号

define([    
'core'
], function () {

return Backbone.Model.extend({

initialize: function (attributes, options) {       
    console.log(attributes);
},

/*  model: Routes,*/
//url: '/apiproxy.php?method=getdirections&rt=',

  parse: function (data) {
    var parsed = [];
        $(data).find('dir').each(function (index) {
        var dir = $(this).find('dir').text();           
        parsed.push({
            dir: dir,               
        });        
    });
    return parsed;
},

fetch: function (options) {
    options = options || {};
    options.dataType = "xml";
    return Backbone.Model.prototype.fetch.call(this, options);
}
});

});

【问题讨论】:

  • 浏览器控制台有错误吗?
  • 否,但 console.log(attributes) 未定义。

标签: backbone.js


【解决方案1】:

通过在实例化时将选项传递给模型来解决。让我感到困惑的是,它们是作为属性而不是模型中的选项出现的。怎么来的?

查看:

    initialize: function (options) {
        this.model = new Direction(options);
    },

型号:

initialize: function (attributes, options) {
    console.log(attributes);

},  
url: function () { 
    //'this' now contains attributes
    var route =  this.get("routeNumber);
    //var route =  this.attributes.routeNumber;
    return '/apiproxy.php?method=getdirections&rt=' + route;      
},

【讨论】:

    猜你喜欢
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 2020-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多