Last active
January 15, 2020 01:59
-
-
Save nowri/bb00a12fe759ea055da7 to your computer and use it in GitHub Desktop.
jQueryでFluxライブラリreduxを使えるようになるPlugin
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
/*! 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; | |
}; | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There's no
isInit = false;
- is it intentional?