javascriptjquerycanjscanjs-control

Pass data from child click to parent event callback in CanJS


In CanJS controller, I am using click event inside another click handler. How can I pass some data to parent handler from child handler

someController=can.Control({
    init:function(element,options){
    //  some code
    },
    '.someButtonSelector click':function(el,ev)
    {
        console.log(this.options.someData) //Returns array of objects
        ev.preventDefault();
        $('#someFormButton').click(function()
        {
            var formData=can.deparam($('someFormSelector').serialize());
            //Want to add formObject in this.options.someData array

        })
    },      
})

I want to put formData into this.options. here this represents object of someController so I cannot use it directly inside the someFormButton click event.

Also want to know if I am following the right approach? Scenario is on clicking the someButtonSelector a form appears. I want to put the formData into current options object


Solution

  • Is adding a click handler within another handler what you really want to do? Your code would mean that a new click handler will be added to #someFormButton every time someone clicks on .someButtonSelector. If #someFormButton is also within the Controls element I think what you'd like to do (adding the serialized data to this.options.formData when clicking #someFormButton) should look something like this:

    var someController = can.Control({
        init:function(element,options){
        //  some code
        },
    
        '.someButtonSelector click':function(el,ev)
        {
            console.log(this.options.someData) //Returns array of objects
            ev.preventDefault();
        },  
    
        '#someFormButton click': function(el, ev) {
            var formData = can.deparam($('someFormSelector').serialize());
            this.options.formData.push(formData);
        }    
    })