mercredi 4 février 2015

trying to change an object with pubsub pattern or through a function

I have this code below. I'm new to object oriented programming and I'm just learning about pub/sub. in the code I thought I was changing the oVars object dynamically. what am i doing wrong?



$(document).ready( function(){
//if checked perform some operation if uncheckec perform a differnt operation
$emitter = $({});
var oVars = {};

$('.checkboxes :checkbox').click(function(){
var checkboxChecked = $(this);
$emitter.trigger("thisBox", checkboxChecked)
});

function whichBox(ovars){
$emitter.on("thisBox", function(e, val){
console.log($(val));
if($(val).is(":checked") && val.id == "withones"){
alert('withones clicked')
ovars[val.id] = true;
}
if(! $(val).is(":checked") && val.id == "withones"){
alert('withones unchecked')
ovars[val.id] = false;
}

if($(val).is(":checked") && val.id == "withoutOnes"){
alert('withones clicked')
ovars[val.id] = true;
}
if(! $(val).is(":checked") && val.id == "withoutOnes"){
alert('withones unchecked')
ovars[val.id] = false;
}

})
}


i want to update the ovars obj every time the checkbox is toggeled so i want oVar to look something like this



ovars{
withones : true, //or false if unclicked
withoutOnes : false, // or true if checked
etc..
}


i want to be able to do later in my code



if(ovars['withones'] == true){
do this;
}
if(ovars['withones'] == false){
do this;
}


I dont know why the code below doesnt work. I put it the obj (oVars) in the paramater so I thought that oVars will be updated because of what i did in whichBox function ovars[val.id] = true;



whichBox(oVars)
console.log("ovars" + oVars)


or why this doesnt work for testing



whichBox(function(oVars){
console.log("ovars" + oVars)
});


jsfiddle for testing


Aucun commentaire:

Enregistrer un commentaire