Prateik
Prateik

Reputation: 341

Javascript error while adding grid using Gridster

$(function ($) {

    var gridster;
    widget_base_width: 240;
    widget_base_height: 240;
    widget_margin_h: 10;
    widget_margin_v: 10;
    gridActive: false;

    this.gridster = $('.gridster ul').gridster({
        widget_margins         : [this.widget_margin_h, this.widget_margin_v],
        widget_base_dimensions : [this.widget_base_width, this.widget_base_height],
        helper                 : 'clone',
        draggable              : {}
    }).data('gridster');

    $(".chart-button").click(function () {
        this.gridster.add_widget('<li id="hideil"><div id="test">heloooooo</div></li>');
    });

});

I am using this code to add the tile using gridster but I am getting error saying :

Uncaught TypeError: Cannot read property 'add_widget' of undefined
(anonymous function)
x.event.dispatch jquery-1.10.2.min.js:22
v.handle jquery-1.10.2.min.js:22

Upvotes: 0

Views: 1713

Answers (1)

Pavel Reznikov
Pavel Reznikov

Reputation: 3208

this object of your click handler is not the same as this object outside of it. Context is different: inside the handler this object is pointing to $('.chart-button'). You can either define a variable outside the handler and use it:

var gridster = $('.gridster ul').gridster(...).data('gridster');

$(".chart-button").click(function () {
    gridster.add_widget('<li id="hideil"><div id="test">heloooooo</div></li>');
});

or you can bind this (override context for handler) to the handler:

this.gridster = $('.gridster ul').gridster(...).data('gridster');

$(".chart-button").click(function () {
    gridster.add_widget('<li id="hideil"><div id="test">heloooooo</div></li>');
}.bind(this));

Upvotes: 2

Related Questions