开发者

disparity of accessing a custom obj's properties in a prototype method when using jquery tmpl

开发者 https://www.devze.com 2023-02-25 05:02 出处:网络
i\'m not quite sure if my approach here is off, or if i just need an elegant way to solve what i\'m doing.

i'm not quite sure if my approach here is off, or if i just need an elegant way to solve what i'm doing.

i've got a custom Javascript object, called Dude in this example.

Dude has 1 property called 'height' and 1 method defined on its prototype called 'reallyTall'

var Dude = function(props) {
    this.height = "tall";
};
Dude.prototype.reallyTall = function() {
    return this.height + " as heck";
};

i'm creating an array of Dudes (with just one item in this example), and would like to use jquery.tmpl() to take my Dudes and append them in some fashion to a div in my HTML. (not caching template for purposes of this simple example)

var guy = new Dude();
jQuery.tmpl("<li>${reallyTall}</li>", guy).appendTo('#foo');

where #foo is an empty <ul> in the HTML

i'd like to keep my Dude objects 'generic' enough so that if someone does not want to use them with jquery.tmpl, t开发者_StackOverflow中文版hey don't have to....meaning, someone may want to achieve something similar to above, but rather do something like:

jQuery("#foo").append('<li>' + guy.reallyTall() + '</li>'));

this is where my issue arises - with the value of this inside of the reallyTall method.

when not using tmpl(), i can access Dude's height property by simply doing

this.height

but when tmpl() is being used, i'd have to access it like so:

this.data.height

i could do something like this in the reallyTall method:

this.height || this.data.height

but that just seems dirty.

i was hoping someone had a better solution to my problem, or can point out if i'm using jquery.tmpl() incorrectly here.

here's a fiddle with my example:

http://jsfiddle.net/FTF5M/2/


Try using ${$data.reallyTall()} in your template.

http://jsfiddle.net/rniemeyer/9CtsV/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号