Created
July 15, 2012 19:28
-
-
Save mwjackson/3118265 to your computer and use it in GitHub Desktop.
extending backbone.js with an explicit controller
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Extending Backbone.js with a Controller class to place logic not belonging in either Models or Views | |
*/ | |
Backbone.Controller = function (options) { | |
this.model = (options && options.model) || {}; | |
}; | |
var controllerMixin = _.pick(Backbone.Model, "extend", "constructor"); | |
_.extend(Backbone.Controller, controllerMixin); | |
var originalView = Backbone.View; | |
Backbone.View = function (options) { | |
originalView.apply(this, arguments); | |
this.controller = options.controller; | |
}; | |
_.extend(Backbone.View, originalView); | |
_.extend(Backbone.View.prototype, originalView.prototype); | |
var MyController = Backbone.Controller.extend({ | |
doMyAjaxRequest: function (someArgument) { | |
$.ajax({ type: "POST", url: "http://whatever", data: JSON.stringify(someArgument), contentType: 'application/json; charset=utf-8' }) | |
.success(function () { | |
// success | |
}) | |
.error(function (result) { | |
// failure | |
}); | |
} | |
}); | |
var model = new YourModel(); | |
var controller = new MyController(); | |
var view = new MyView({ model: model, controller: controller }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment