So, I am a java developer, trying to not write too much java code in javascript. I have read various resources about javascript (like http://chimera.labs.oreilly.com/books/1234000000262/ch04.html ), but I still can't figure out a neat and nice way to do this right.
So, basic problem is:
- click 'delete' button (there will be many delete buttons on the page)
- open bootstrap modal dialog, which is a underscore template
- bind action to buttons
- if ok is clicked, make an ajax request
So, this is a solution that works partially so far. I am having problems calling functions from the ajax success callback. If I try to use 'this', it has the wrong context. I could probably store this in another variable (like 'that'), but that would definitely that nice.
Furthermore I am not quite sure this code looks that good, considering what I have read in above mentioned book
function DeleteHandler() {
var obj = {
init: function () {
_.bindAll(this, 'render', 'close', 'submit');
this.$main = $('#main');
// get underscore template
this._template = _.template($('#delete-template').html());
// bind function to delete button
this.$main.on('click', '.delete', this.render);
},
render: function(e) {
e.preventDefault();
//render the template and bind button actions
this.$content = $(this._template({title: 'moe'}));
this.$content.on('click', '.ok', this.submit);
this.$content.modal('show');
this.$endpoint = $(e.target).attr('endpoint');
},
close: function () {
this.$content.modal('hide');
},
submit: function() {
$.ajax({
url: this.$endpoint,
type: 'DELETE',
success: function(data,textStatus){
// call close function here! but how?!?
},
});
}
}
return obj;
};
Now I can use something like this
<span class="delete" endpoint='http://....'>delete</span>
<script type="text/javascript">
$(function($) {
DeleteHandler().init();
});
</script>
I would be really happy if I could just call my function like this:
DeleteHandler.init();
is this possible? I will be using this function multiple times on the page, so I can't just use a literal instead of the function.
edit: I have found some sort of workaround to make the ajax callback happen: You can pass a context to the jquery ajax literal:
If I use something like this:
$.ajax({
url: this.$endpoint,
type: 'DELETE',
context: this,
success: function(data,textStatus){this.$update.html(data); this.close();},
}
I can actually call this.close() in the success callback. Probably not a very nice solution. But probably someone has a better idea?
initcode into a constructor function, and the other methods intoTheConstructor.prototype.methodName, then instancing withnew TheConstructor(args). Which method you choose to implement "pseudo-classes" is partly a matter of style. Maybe you could give more details as to why your current code doesn't "feel right".