简体   繁体   中英

backbone passing parameters to a model url

In my controller I'm passing in a parameter called 'url' to a view. This is passed successfully into the initialize function. Next when I create my model I would like to pass the same parameter into the model to use as the rooturl.

Below is what I have tried but I got the following error message:

A "url" property or function must be specified 

This seems like the parameter is not being passed to the model (undefined) or I'm not calling it correctly in the model. What I'm I doing wrong here?

Note: console.log(options.url) in the initialize function view confirms the parameter is passed successfully from the controller to the view, the issues is from the view to the model where it is undefined.

Controller:

var myview = new NewView({
           url:"api/"
       })**

View:

  var myview = Backbone.Marionette.ItemView.extend({

        initialize: function (options) {
            this.url = options.url;
            this.model.fetch();
        },


    model: new myModel({
            url: this.url
        }),

myModel:

var myModel = Backbone.Model.extend({
  urlRoot: function(){ return this.get('url') }

});

You are trying to fetch your model with an empty url.

When you call:

initialize: function (options) {
  this.url = options.url;
  this.model.fetch();
}

fetch here, you don't have the url for the model. So, you could do:

initialize: function (options) {
  this.url = options.url;
  this.model.set({url: this.url});
  this.model.fetch();
}

When writing

model: new myModel({
        url: this.url
    }),

the view is not yet initialized

You can instantiate the model in the view's initialize method

initialize: function (options) {
        this.url = options.url;
        this.model = new myModel({
            url: this.url
        })
        this.model.fetch();
    },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM