Which strategy makes more sense in this jQuery plugin? [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm making a jQuery plugin that displays alerts on the page. The plugin itself inserts the alert markup into the DOM. Since the jQuery way is to make everything return this to maintain chaining, I've run into an interesting issue I'd like feedback on. I'm trying to decide between the following two options.
Option One:
$("#content").alert('prepend', {type:'error', message:'This is an error'})
This looks pretty simple. An alert is prepended to the beginning of the #content DOM element. The problem is that it's unclear what is returned. It would make sense to return the alert element that was just created, but that kind of goes against the jQuery way.
Option Two:
$("<div>").alert({type:'error', message:'This is an error'}).prependTo("#content")
This way seems less clear and less intuitive, but it's more inline with the jQuery way of doing things, and it's clear what element is going to be returned.
So which options would you choose? My concern is that most users may not know that you can do $('<div>') to create a new element. On the other hand, I don't know of any well-known projects whose jQuery plugin methods return elements other than the elements they're invoked on, but perhaps there are. Thoughts?

I would just put it in the jQuery namespace (instead of on its prototype):
$.alert({type:'error', message:'This is an error'}).prependTo("#content");
In addition, you might consider asking for a selector/DOM node/jQuery object, instead of having the user prepend it themselves:
$.alert({
parent: '#content', // or $('#content') or document.getElementById('content')
type: 'error',
message: 'This is an error'
});

If your alert system is meant to be a popup-like or modal-like system, the user shouldn't have to specify a container. However, you can allow him to pass a container to insert your alertbox in:
$.alert({
type: 'error',
message: 'This is an error',
container: $(...) // Optional
});
It would return your plugin instance, or the alert container.

No, jQuery does not always return this. Chainability means only that you should return the instance itself if there's no result of your method.
For example, the clone() returns a new jQuery instance too; so there's nothing wrong with it. If you say "it's unclear", just document it, or rename the method to e.g. "$.fn.getAlert".
Yet, you must choose the signature of your method. The first option is like having a mandatory parameter for the container. If you like to make it optional, you might make the alert system a static method: $.createAlert(...) with an optional parameter.

Related

Uncaught SyntaxError: Unexpected token . AKA how to check for an Id in jQuery [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I need to know how to check for a CSS Id (or a class) if its enabled or disabled in jQuery. For example, let's say I have two Ids, sectionA and sectionB on some form pointing to two different sections of markup.
Now, I have a common reusable JS function that does some work based on which of the sections was referenced(activated) by the user. Think of user making entries on the some input fields of sectionA or viceversa. So I am trying to do something like this (please pardon my syntax):
function doSomething() {
if $('#sectionA').Enabled { //I know its not real syntax {
var inp = document.getElementById('sectionA');
}
else if ('#sectionB').Enabled {
var inp = document.getElementById('sectionB');
}
}
etc.
Sorry if this is too trivial a question. I know the question is hard to visualize at first but I wish I could draw it out. I certainly appreciate any helpful hints.
jQuery selectors us the same syntax as CSS does, so you can just use the :enabled pseudo-class selector:
if ($('#sectionA:enabled')) { ... }
But, after reading your comments, I'm not sure enabled is what you are looking for. You may want :active, which would be:
if ($('#sectionA:active')) { ... }
You could also write both of these like this:
if ($('#sectionA').is(':enabled')) { ... }
if ($('#sectionA').is(':active')) { ... }
Also, if you are going to use jQuery, why not use it here as well:
document.getElementById('sectionA')
Can just be:
$('#sectionA')
That's because the code you have provided has syntax errors like
. else if ('#sectionB').Enabled
Should be
. else if ($('#sectionB:enabled'))
Use brackets with if else conditions.. And Check the $ sign there, also .Enabled is nothing in jQuery, if it's a check box then use .prop('checked') or .is(':enabled')

How can I call an object method using a function argument? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
So I asked a similar question before... I wanted to know how to argue for the css property in a document.element.style.property=value. The solution was simple, and almost made sense --but clearly I didn't understand it entirely or I'd know trying the same solution for .element doesn't work.
Here is my code:
function appendElement(handle){
element=document[handle]('div');
document.body.appendChild(element);
}
This way I could choose to create a new element or shift an existing one based on id or class or index appearance or whatever. Of course even without knowing the correct way to do this, the code I have above looks wrong to me, but it's the best I can do without some assistance.
EDIT: Test case
/* The core instructions */
element=document.createElement('div');
document.body.appendChild(element);
/* the choosy version */
function appendElement(handle){
element=document[handle]('div');
document.body.appendChild(element);
}
appendElement(createElement);
element.innerHTML="third text";
/* SHOULD move the 'text' div under the 'third text' div*/
appendElement(getElementById('first'));
<div id="first">text</div>
<div>second text</div>
Edit
In this line appendElement(getElementById('first'));you are not passing a function as you want, you are passing the result of call undefined with the param 'first', because it can't find a function in that context or a global function called getElementById (so it will be undefined), furthermore your are trying to execute undefined passing it a string... this is going to raise an error, and in the case in which function existed (i.e you pass document.getElementById('first')), then you will be passing the returned value of executing that function instead of the function.
If you want to pass a function you should pass a function, thats is appendElement(document.getElementById), without calling it with an argument, but I think you are going to need to pass a selector to that function to accomplish what you are trying to do. So
the code will be something like this:
function appendElement(handle, selector){
element=handle.call(document, selector);
document.body.appendChild(element);
}
appendElement(document.getElementById, 'first');
<div id="first">text</div>
<div>second text</div>
call allows you to execute a function as a method and specify which object will be the receptor of that calling. Here is more info
I didn't understand your need.
But, if handle is equals to 'createElement', which is a property of document, your code will run.

What is 'catcomplete' in jQuery's autocomplete plugin? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
The jQuery UI autocomplete plugin uses the catcomplete function. I'm new to the jQuery syntax. How can I to read it?
$("#searchTextBox").catcomplete({
minLength: 1,
source: $("#searchTextBox").data("url"),
open: function () {
$(".ui-autocomplete").css({
left: $(".ui-autocomplete").position().left - 50 + "px",
top: $(".ui-autocomplete").position().top - 12 + "px"
});
},
select: function (event, ui) {
/* Code */
}
});
What is catcomplete?
catcomplete is a property that appears on jQuery objects. It is not part of core jQuery so there is presumably some other script on the page that is adding it.
How does jQuery's autocomplete call it?
I can't find catcomplete mentioned anywhere in the documentation for autocomplete, so it probably doesn't. It just modifies the CSS of elements in the page with class names that suggest they are normally influenced by autocomplete.
What are minLength, source, open and select?
Properties of the object that gets passed as an argument to the catcomplete complete function. You should read the catcomplete documentation to find out what they mean.
Who decided their name?
The author(s) of catcomplete
Which part of the code knows how to use them?
The catcomplete script
Are they a part of standard jQuery?
No.
Is catcomplete a function?
Yes, it has (…) after it to call it and does not (presumably) throw an exception.
What is $("#searchTextBox").Example({})? doing? Am I defining an array and passing it to a function called Example?
No. You are creating an object. An array would be [].
Or am I defining a function called Example which initializes an anonymous Array?
No. That would be:
function Example() {
var foo = [];
}

Easier multiple value changes with jQuery [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am really in need of this one, because I cann't manually type loads of options for admin panel. Hence I need a quick way to fetch each input/select and add value as I want.
Here's looong sample for one option field:
$("select[name=big_proceed]").val("true");
$("select[name=proceed_action]").val("");
$("input[name=choice_premium]").val("Premium <span>Code</span>");
$("input[name=big_proceed_pts]").val("");
$("#settings_proceed input, #settings_proceed select").each(function () {
databaseData($(this));
});
I thought something like this may work but apparently I was wrong. Here's sample:
$("#settings_proceed :input").each(function () {
$(this)
.eq(0).val("true")
.eq(1).val("")
.eq(2).val("Premium <span>Code</span>")
.eq(3).val("");
databaseData($(this));
});
Any suggestions for me ?
From the jQuery documentation:
.eq(index): Reduce the set of matched elements to the one at the specified index.
Hence your second example doesn't work as intended because $(this) only matches one element (that's the intention behind the .each()). You could rewrite the code like so:
var values = ["true", "", "Premium <span>Code</span>", ""];
$("#settings_proceed :input").each(function(i){
$(this).val(values[i]);
databaseData($(this));
});
However, this approach makes the code hard to read and error-prone because it assumes a fixed order of the HTML elements (what if you change the order of the input fields but forget to adjust the JS accordingly?). So you really should "manually" add IDs to your input elements and select them by their ID and not their index.
As #David Thomas pointed out, some sample HTML would be quite helpful here, but without knowing any further details of what you're trying to do I'd suggest the following:
var values = {
big_proceed: "true",
proceed_action: "",
choice_premium: "Premium <span>Code</span>",
big_proceed_pts: ""
};
$.each(values, function(key, value){
$("#settings_proceed").find("[name='"+key+"']").val(value);
databaseData($(this));
});
That way you can neatly define all the values in one object and let jQuery safely do the rest.

Which is the best way to validate the parameters received by a function [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Create: function (title, text, orientation, trigger, layout) {
$(this).attr
},
The trigger parameter must receive one of two very specific words: 'hover' or 'click' and I can't think of a good way to ease the implementation of this function.
I did think of some solutions:
I can try to validate the parameter once already inside in the function and return a 'console.info' right after breaking the execution in case a wrong parameter has been sent, informing the developer of his mistake
I could create a ENUM and provide it as an interface for the developer (which would still make the developer have to read it in order to use it properly)
Occurred me while typing this post that I could just set standard values for the options, hence they're optional.
I just don't know which one is the best approach in a situation like this. Can I assume that the developer that is willing to use the code MUST read the code to find the best way to implement it or (as I suppose) I should be concerned with validations like the ones I described? Also which one is the best?
Comparing straight up with strings is a common practice in javascript. ENUM-like structures, although easy to implement, are usually not very used because you either have to define your ENUM-like as globals or do something like:
application.enums.myObject.hover= 1;
application.enums.myObject.click= 2;
myObject= new application.constructors.MyObject();
myObject.create(title, text, orientation, application.enums.myObject.hover, layout)
In this manner only application is global, but typing application.enums.myObject is a pain.
How to handle the error:
Option 1: throw an exception:
Create: function (title, text, orientation, trigger, layout) {
if (trigger !== "hover" && trigger !== "click") {
throw "error: invalid parameter trigger";
}
},
This will crash your script unless you have a catch clause somewhere. In some cases crashing the party is better than not providing a way to know what is wrong. If you intend on catching these exceptions (instead of letting them just crash the script) I recommed doing it properly by making classes for your errors and such.
Option 2: Return null.
Create: function (title, text, orientation, trigger, layout) {
if (trigger !== "hover" && trigger !== "click") {
return null;
}
},
This approach works better if you are going to use the return value of the function. When debugging you will see "object has no property named X" error when trying to use the return value (or your value will be coerced into the "null" string if you use it as such).
Option 3: Quietly ignore the error and do nothing. Either your script will crash on its own or it will do nothing. Not recommended
Observations:
1 - do not use the console object in production code. It's not part of the standard and IE does not expose it to the web page unless you open the developer console
2 - do not start your function names with an upper case letter unless it's a function that should be called with the 'new' keyword (ie a constructor function).

Categories

Resources