I create an object with "new", initialize it and subscribe to it's event with $(this).trigger({type:"myevent", field1:val1})
, like (here - jsfiddle ), and it works:
var Users = function (selector) {
var that = this;
var myButton;
//function to trigger
function add(name) {
console.log("before trigger for: $('"+selector+"') with ["+name+"]")
$(that).trigger({
type: "user-added",
name: name,
date: new Date(),
});
}
$(selector).click(function () {
add($("#name").val());
});
};
My problem is that I am interested to pass the selector
in a separate function init
(another jsfiddle):
var Users = function () {
var that = this;
var mySelector;
//function to trigger
function add(name) {
console.log("before trigger for: $('" + mySelector + "') with [" + name + "]")
$(that).trigger({
type: "user-added",
name: name,
date: new Date(),
});
}
function init(selector) {
mySelector = selector;
$(selector).click(function () {
add($("#name").val());
});
}
return {
init: init
};
};
In this case the code is breaking:
When the event is triggered, the that
object the function sees looks like
Users {}
,
and not updated like in the working sample:
Users {jQuery11111210404012482791554801678404482030027643403015099466: Object}
,
so jQuery does not trigger the event.
Sure I can set that
in init()
, or initialize the object in the constructor to solve the problem, but it drives me crazy why the "that"
member does not get hooked up to the actual object if I set it in the constructor and hookup to the event in an inner function, but does work if I hookup to the event in the same function.
Thanks.