Skip to content

Instantly share code, notes, and snippets.

@nowri
Last active January 15, 2020 01:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nowri/bb00a12fe759ea055da7 to your computer and use it in GitHub Desktop.
Save nowri/bb00a12fe759ea055da7 to your computer and use it in GitHub Desktop.
jQueryでFluxライブラリreduxを使えるようになるPlugin
/*! jquery.redux.js | Copyright (c) 2015 nowri | The MIT License (MIT) */
(function(factory) {
if(typeof exports === 'object') {
factory(require('jquery'));
} else if(typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else {
factory(jQuery);
}
}(function($) {
var newActions,
store,
triggerKeys,
isInit;
$.reduxInit = function(_actions, _store) {
if(isInit) {
throw new Error("jquery.redux still initialized");
}
isInit = true;
triggerKeys = [];
newActions = {};
store = _store;
$.each(_actions, function(key, action) {
triggerKeys.push(key);
newActions[key] = function() {
var act;
act = action.apply(this, arguments);
if(typeof act === "function") {
act(store.dispatch, store.getState);
} else {
store.dispatch(act);
}
}
});
return $;
};
$.fn.redux = function(type) {
var $elems = this;
var unsubscribe = $elems.data("__reduxUnsubscribe__");
if((type === "on" || type === "off") && typeof unsubscribe === "function") {
unsubscribe();
$.removeData($elems, "__reduxUnsubscribe__");
}
if(type === "on") {
unsubscribe = store.subscribe(function() {
$elems.trigger("reduxChange", [store.getState()]);
});
$elems.data("__reduxUnsubscribe__", unsubscribe);
triggerKeys.forEach(function(key) {
$elems.on("redux:" + key, function() {
newActions[key].apply(null, Array.prototype.slice.call(arguments, 1));
});
});
} else if(type === "off") {
triggerKeys.forEach(function(key) {
$elems.off("redux:" + key, "**");
});
}
return this;
};
}));
@andrevinsky
Copy link

There's no isInit = false; - is it intentional?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment