Question

The goal

Call UserModel within AuthenticationView with Backbone + Sprockets.

The problem

I just don't know a good way to do that.

The scenario

This is my view (assets/js/views/AuthenticationView.js):

var AuthenticationView = Backbone.View.extend({
    el: $('.authentication-form'),
    events: {
        'keyup input[name=email]'       : 'validationScope',
        'keyup input[name=password]'    : 'validationScope',
        'submit form[data-remote=true]' : 'authenticate'
    },
    render: function() {
    },
    authenticate: function() {
        // Here I'm going interact with the model. 
    }
});

And that's my model (assets/js/models/UserModel.js):

var UserModel = Backbone.Model.extend({
    url: '/sessions'
});

The question

How can I make the interaction between the view and the model?

Remember: they're in separated files.

Was it helpful?

Solution

Getting the constructors together would be step 1 -- separate files don't matter, you can use Browserify/requirejs or just throw these things in global scope. From there, since passing an object into a view constructor with the property name 'model', automatically assigns the value to the view's this.model. So if we have an initialize method in our view, we can see:

initialize: function (options) {
  console.log(this.model); // User instance
  this.model.on('update', function () {});
}

And so we can pass in an instantiated model into the view via an object's model property:

var model = new UserModel(); 
var view = new AuthenticationView({ model: model });

OTHER TIPS

http://www.joezimjs.com/javascript/lazy-loading-javascript-with-requirejs/ here is great article about js modules lazy loading with examples used backbonejs and requirejs

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top