Created
April 30, 2015 10:26
-
-
Save ertrzyiks/0fbb14d609c2eb95378d to your computer and use it in GitHub Desktop.
Middleware for backbone.sync
This file contains 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
define(['backbone'], function (Backbone) { | |
"use strict"; | |
var middleware = [], | |
BackboneSync = Backbone.sync; | |
function passThroughMiddlewares(list, data, done) { | |
if (0 === list.length) { | |
done(null, data); | |
return; | |
} | |
var cb = list.shift(); | |
cb.call(data.scope, data.method, data.model, data.options, function (err, method, model, options) { | |
if (err) { | |
throw err; | |
} | |
var modifiedData = { | |
scope: data.scope, | |
method: method, | |
model: model, | |
options: options | |
}; | |
passThroughMiddlewares(list, modifiedData, done); | |
}); | |
} | |
Backbone.sync = function (method, model, options) { | |
var list = middleware.slice(), | |
data = { | |
scope: this, | |
method: method, | |
model: model, | |
options: options | |
}; | |
passThroughMiddlewares(list, data, function (err, data) { | |
BackboneSync.call(data.scope, data.method, data.model, data.options); | |
}); | |
}; | |
return { | |
addHandler: function (cb) { | |
middleware.push(cb); | |
}, | |
removeHandler: function (cb) { | |
var index = middleware.indexOf(cb); | |
if (index > -1) { | |
middleware.splice(index, 1); | |
} | |
}, | |
removeAllHandlers: function () { | |
middleware.length = 0; | |
}, | |
getHandlersCount: function () { | |
return middleware.length; | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment