์ค๋์ ๋ฐ์ค๊ณผ ๋ฐฑ๋ณธ์ ์ฌ์ฉํ์ฌ ์ฝ๋๋ฅผ ์์ฑํ๋ ๋์ ๋ช ๊ฐ์ง ํจ์๋ฅผ ๋ํํด์ผํ์ต๋๋ค. underscorejs.org์์ ๋ค์ ์์ ๋ฅผ ๋ณด์์ต๋๋ค.
var hello = function (name) {return "hello :"+ name; };
hello = _.wrap (hello, function (func) {
return "before,"+ func ( "moe") + ", after";
});
์๋
ํ์ธ์();
=> 'before, hello : moe, after'
๋ ๋ฒ์งธ ๋ง์ง๋ง ์ค์
ํจ์ ํธ์ถ์ด ๋ค์๊ณผ ๊ฐ์ผ๋ฉด
hello ( "umar");
๋๋ ๋
ผ์์ด ์ธ๋ถ์์ ๋์จ๋ค๋ ๊ฒ์ ์๋ฏธํฉ๋๋ค.
Wrap์ ์ด๋ฏธ ๋๋ถ๋ถ์ ์์ ์ ์ฒ๋ฆฌํฉ๋๋ค. ๋ฉ์ ์์ค๋ ์ฝ์ ์์๋ ๋งค์ฐ ์งง์ต๋๋ค. ๋๋ ์๋์ ํ์ฅ ์์ ๋ฅผ ์ดํด๋ณผ ์ ์์ต๋๋ค.
var greet = function(name, language){
var response
if (language === "sp") {
response = "Hola"
} else if (language === "fr") {
response = "Bonjour"
} else {
response = "Hello"
}
return response + " " + name
}
greet("Ted", "fr"); // => "Bonjour Ted"
greet = _.wrap(greet, function(old_greet, lang){ return old_greet("Ted", lang); } );
greet("sp"); // => "Hola Ted"
๋น ๋ฅธ ์๋ต์ ๊ฐ์ฌ๋๋ฆฝ๋๋ค. ๋งค์ฐ ๋์์ด๋์์ต๋๋ค.
๋ฐฑ๋ณธ์ ์ฌ์ฉํ์ฌ ์ํฐํ๋ผ์ด์ฆ ์ฑ์ ๊ฐ๋ฐํ๊ณ ์์ต๋๋ค.
view.js
var view = Backbone.View.extend ({
authorizeCreateAction : ํจ์ () {
// ์ฌ๊ธฐ์ "this"๋๋ณด๊ธฐ๋ฅผ ๊ฐ๋ฆฌ ํต๋๋ค.
this.createAlert : _.wrap (this.createAlert, function (_createAlert, _type) {
// ์์ฑ ์์
์น์ธ
return _createAlert (_type);
});
},
createAlert : function (type) {
//๋ฌธ์ :
// ์ฌ๊ธฐ์ "this"๋ [window global]์ ๊ฐ๋ฆฌ ํต๋๋ค.
}
});
createAlert ํจ์๋ฅผ ์ง์ ํธ์ถ ํ ๋ createAlert ํจ์ ๋ด๋ถ๋ฅผ ์ฐธ์กฐํ์ญ์์ค.๋ณด๊ธฐ๋ฅผ ๊ฐ๋ฆฌํค๊ณ ์์์ง๋ง ๋ํผ ํจ์๋ฅผ โโ์์ฑํ์ ๋ [window global]์ ๊ฐ๋ฆฌ ํค๊ธฐ ์์ํ์ต๋๋ค.
"๋ณด๊ธฐ"๋ฅผ ๊ฐ๋ฆฌ ํค๋๋ก ์ฐธ์กฐ๋ฅผ ๋ณ๊ฒฝํ๊ณ ์ถ์ต๋๋ค.
๋๋ ๋ฐ์ค์ ์ฒ์ ์ฌ์ฉํฉ๋๋ค. ์ง๋ฌธ์ด ๊ด๋ จ์ด ์์ผ๋ฉด ๋ฌด์ํ์ญ์์ค.
BTW ๋ฐ์ค์ ๊ต์ฅํฉ๋๋ค
์๋์ ๊ฐ์ ์ปจํ
์คํธ๋ก _createAlert
๋ฅผ ํธ์ถํด์ผํฉ๋๋ค. ๋์์ด๋๊ธฐ๋ฅผ ๋ฐ๋๋๋ค. :)
return _createAlert.call(this, _type);
๋ฐ์ค _wrap์ ํ๋์ ๋งค๊ฐ ๋ณ์ ๋ง ์ง์ํ๋ ๊ฒ ๊ฐ์ต๋๋ค. ๋์ ๋ค์์ ์ฌ์ฉํ์ญ์์ค.
fn = (function (fn, before, after, self) {
return function () {
if (before) before.apply (self, arguments);
var res = fn.apply (self, arguments);
if (ํ) after.apply (self, arguments);
๋ฐํ ํด์๋;
}
}) (fn, ์ด์ , ์ดํ, this)
ํด๋น zarehb์ ๋ถ๋ถ์ ์ฌ์ฉํ ์๋ ์์ต๋๋ค.
tnx megawac, partial์ ์ด์ ๋ฐ ์ดํ ํจ์๋ฅผ ํธ์ถํ์ง ์๋ ์ธ์๋ฅผ ๋ฏธ๋ฆฌ ์ฑ์ฐ๋ ๋ฐ ๋ ์ ํฉํฉ๋๋ค.
๋ฉ์ _.partial
fyi๋ฅผ ํตํด ๊ตฌํ๋ฉ๋๋ค.
fn = _.partial(function(fn, before, after, self) {
var args = _.rest(arguments, 4);
if (before) before.apply(self,args);
var res = fn.apply(self,args);
if (after) after.apply(self,args);
return res;
})(fn, before, after, this )
๊ทธ๊ฒ์ ์ ํํ๊ณ ์๋ํ์ง๋ง, ๋๊ตฌ๋ ์ง ์์ํ js ์๋ฃจ์ ์ ์ํ๋ ๊ฒฝ์ฐ์๋ ํนํ ๋ฐ์ค์ ์ฌ์ฉํ๋ ๊ฒ์ด์ด ๊ฒฝ์ฐ ์ด๋ค ์ด์ ๋ ์ ๊ณตํ์ง ์์ต๋๋ค.