BackboneJS - 无法动态更新集合URL

时间:2017-03-22 11:00:51

标签: backbone.js backbone-collections

我正在尝试将模拟数据生成到我的应用程序中。根据要求,我的用户可以设置json的大小。为此,我将用户带到新页面并从用户获取值。说smallmediumlarge。一旦用户定义了大小,我就会更新我的收藏集的url链接:

var api = "movies"; //default. later setting by dynamic

    var getURL = function( size ){

        console.log('api is', api);

        return api;

    }

    var Theater = {
        Models: {},
        Collections: {},
        Views: {},
        Templates:{}
    }

    Theater.Models.Movie = Backbone.Model.extend({});

    Theater.Collections.Movies = Backbone.Collection.extend({
        model: Theater.Models.Movie,
        urlRoot : getURL(),
        url : function(){
            console.log( "json from",  "scripts/data/" + this.urlRoot+".json" );
            return  "scripts/data/" + this.urlRoot+".json"; //dynamic
        },
        initialize: function(){
            console.log("Movies initialize");
        }
    });

这是视图部分:

 Theater.Templates.simulator = _.template($("#tmplt-simulator").html());
    Theater.Views.Simulator = Backbone.View.extend({
        el: $("#mainContainer"),
        events :{
            "click .radioBtn" : "setDataSize"
        },
        template : Theater.Templates.simulator,
        initialize: function () {
            _.bindAll(this, 'render');
            this.render();
        },
        render: function () {
            this.$el.empty();
            return $(this.el).append(this.template()) ;
        },

        setDataSize : function(e){
            e.preventDefault();
            var size = e.target.value;
            api = size; //updating the URL but not working when go back to home
        }

    })

除了上述细节之外,还有完整的代码:full code

是否有人帮我处理这种情况?

提前感谢。

1 个答案:

答案 0 :(得分:2)

集合并非真正具有由Backbone处理的内置urlRoot属性。所以你定义的是一个自定义属性,只在创建集合构造函数时才计算一次。

你应该做的是:

url: function(){
    return  "scripts/data/" + getURL() + ".json";
    // ------------------------^ something that is actually dynamic
},