javascript - Passing event to callback function -
i using summernote api (http://summernote.org/#/deep-dive), , using callback onkeyup follows:
$('#summernote').summernote({ height: 150, onkeyup: myfunction });
for html:
<textarea id="summernote"></textarea>
i defined myfunction ...
var myfunction= function(e) { var num_chars = $(e.target).text().length console.log(num_chars); }
now pass parameters .bind() myfunction. when
onkeyup: myfuntion.bind(1,2)
$(this) or e.target not work, has how params shuffled around when use .bind()
how maintain e.target functionality , pass data function bind?
any appreciated.
you can't use bind
in manner. you're trying partially apply arguments right side of function (because want first argument event). in addition, bind(1, 2)
sets this
1
, passes 2
invoked function. looks want this:
onkeyup: _.partialright(myfunction, 1, 2); function myfunction(event, data1, data2) { var numchars = $(e.target).text().length; console.log(numchars); }
however, might lose this
binding. if want preserve should use bind
again, this:
onkeyup: _.partialright(myfunction.bind($), 1, 2); // bind $ function myfunction(event, data1, data2) { var numchars = this(e.target).text().length; // because $ }
_
in example lodash.
the reason (and can't use bind it) because bind partially applies left. means pass arguments first, , arguments passed bound function when invoked passed afterwards. in other words, original set up, this:
myfunction(2, event); // "this" 1
rather want, is:
myfunction(event, 1, 2); // "this" undefined behaviour
to need partially apply function above, give desired behaviour. reason use partialright
because causes arguments passed invoked function applied first , arguments passed bind. if did not use partialright
, instead used partial
, instead this:
myfunction(1, 2, event); // "this" undefined behaviour
this bit might bit beyond reach
bind
sets thisbinding of function this
provided. arguments passed partially applied (from left) function, , resultant function returned. means next time invoke resultant function, invoke function thisbinding supplied in bind, plus arguments supplied in bind, plus arguments passed welll
Comments
Post a Comment