could you please tell me how to load precomplied templates .I googled it and find a solution .Now I don't know how to use this function.could you please tell me how to use this function ?
code:
http://goo.gl/ALfkzf
Backbone.Marionette.TemplateCache.prototype.loadTemplate = function (templateId, callback) {
var tmpId = templateId.replace("#", ""),
url = "/app/templates/" + tmpId + ".html";
$.get(url, function (templateHtml) {
compiledTemplate = Handlebars.compile($(templateHtml).html())
callback.call(this, compiledTemplate);
});
};
Backbone.Marionette.Renderer.renderTemplate = function (templateId, data) {
var renderer = $.Deferred();
Backbone.Marionette.TemplateCache.get(templateId, function(template){
var html = template(data);
renderer.resolve(html);
});
return renderer.promise();
};
I am trying to load html file which is inside the directory ? template/test.html
var ToolItemView = Backbone.Marionette.ItemView.extend({
template: 'template/test.html',
});
The code that you are trying to use, replaces default HTML mechanism in Marionette.
'template/test.html' will be translated to "/app/templates/template/test.html.html", which I guess is not what you want (Either change url generation, or template pointer)
Your Backbone code, does not assume, that "test.html" was precompiled on contrary compilation is happening on the client, following GET response, is this what you want?
Regarding Backbone override use, it should be called before you try to render your ToolItemView, so basically you can call this code anywhere before ToolItemView render.
Related
I have two server side php scripts:
1: /addit.php - which creates a pdf file on server based on current ID given
2: /viewit.php - which downloads the pdf file to the browser window.
Both these scripts work fine btw.
However I want to combine a single onclick function to run "addit.php" and then view the file by opening the file "view.php".
So I am using the original code that was creating the file ok and then adding in a window.location but they won't work together. If I remove the window.location the first part of code works fine, If I include it, the first part stops working and only the window.location works.
Sorry for being stupid, thanks.
function download_invoice() {
$(document).on('click','.downloadit',function(id){
var current_element = $(this);
var id = $(this).attr('id');
var ida = $(this).attr('id')+"A";
var idicon = $(this).attr('id')+"icon";
$.post('myaddress/addit.php',
{ list_entry_id: id },
$("#infobox_data_button2").fadeTo(1001,.33)
);
});
window.location="myaddress/viewit.php";
};
You should move window.location="myaddress/viewit.php"; to ajax callback as below. Otherwise it fires before you get response from server.
$.post('myaddress/addit.php',
{ list_entry_id: id },
function() {
$("#infobox_data_button2").fadeTo(1001,.33);
window.location="myaddress/viewit.php";
}
);
The window.location is out of the event. While you run the ajax (asynchronous) to 'myaddress/addit.php' the redirect will occur killing the process.
You need to put the window.location in a success callback, therefore in the event.
function download_invoice() {
$(document).on('click','.downloadit',function(id){
var current_element = $(this);
var id = $(this).attr('id');
var ida = $(this).attr('id')+"A";
var idicon = $(this).attr('id')+"icon";
$.post('myaddress/addit.php', { list_entry_id: id }, function(data){
$("#infobox_data_button2").fadeTo(1001,.33);
// Here!
window.location="myaddress/viewit.php";
});
});
// Abandoned
//window.location="myaddress/viewit.php";
};
I'm currently working on a project using jQuery and Ajax to load in content from local html files to my single page site. I've also got a JSON file that I'm trying to incorporate into the files being loaded in with jQuery and Ajax.
I'm using hash urls to keep the pages separate. This is the code I'm using:
//other cached links
var pageLinks = $(".pageLink");
if(window.location.hash) {
var hash = window.location.hash.replace("#", "");
loadPage(hash + ".html");
} else {
loadPage("index.html");
}
pageLinks
.click(function(){
var iid = $(this).attr("id");
loadPage(iid + ".html");
});
function loadPage(resource) {
window.location.hash = resource.replace(".html", "");
$.get("pages/" + resource, function (data) {
content.html(data);
});
}
//this makes sure the contents of hash in the url is loaded in the page
if(window.location.hash) {
var hash = window.location.hash.replace("#", "");
loadPage(hash + ".html");
} else {
loadPage("index.html");
}
This is how I'm putting my JSON data into the page:
function FooBar() {
this.foo;
this.barLinkTemplate;
}
var fooBar = new FooBar();
$(document).ready(function (){
fooBar.contentDiv = $("#fooContent");
fooBar.barDiv = $("#bars");
$.when(
$.getJSON('data/music.json'),
$.ajax('components/components.html')
).done( function(data, templateData) {
var templateHTML = $(templateData[0]);
fooBar.barLinkTemplate = Handlebars.compile( templateHTML.find("#barLinks").html() );
fooBar.data = data[0].foo;
fooBar.barDiv.html( fooBar.barLinkTemplate( data[0].bars ));
));
});
The Ajax loads just fine, hashes and all. However, nothing from my JSON file is loaded into the page. I think I've narrowed my problem down (at least I hope) to one bit of code. If I comment out the last if/else statement (above), the JSON is loaded in the first page (only the first page). If I click on any link, and I navigate back to that page, the JSON data is gone. I have to actually reload the page for the data to reappear.
Without that if/else statement, I lose the ability to load the page content from the hash in the url--though the links still work fine.
I've been googling, but I haven't seen anything similar to the problems I'm having. Any help is appreciated. Thanks!
I am new to working with AJAX and have some experience with Java/Jquery. I have been looking around for an solution to my problem but i cant seem to find any.
I am trying to build a function in a webshop where the product will appear in a popup window instead of loading a new page.
I got it working by using this code:
$(".product-slot a").live('click', function() {
var myUrl = $(this).attr("href") + " #product-content";
$("#product-overlay-inner").load(myUrl, function() {
});
$("#product-overlay").fadeIn();
return false;
});
product-slot a = Link to the product in the category page.
product-content = the div i want to insert in the popup from the product page.
product-overlay-inner = The popup window.
product-overlay = The popup wrapper.
The problem that i now have is that my Javascript/Jquery isnt working in the productpopup. For example the lightbox for the product image or the button to add product to shoppingcart doesnt work. Is there anyway to make the javascript work inside the loaded content or to load javascript into the popup?
I hope you can understand what my problem is!
Thank you in advance!
EDIT: The platform im using has jquery-ui-1.7.2
I know this is an old thread but I've been working on a similar process with the same script loading problem and thought I'd share my version as another option.
I have a basic route handler for when a user clicks an anchor/button etc that I use to swap out the main content area of the site, in this example it's the ".page" class.
I then use a function to make an ajax call to get the html content as a partial, at the moment they are php files and they do some preliminary rendering server side to build the html but this isn't necessary.
The callback handles placing the new html and as I know what script I need I just append it to the bottom in a script tag created on the fly. If I have an error at the server I pass this back as content which may be just a key word that I can use to trigger a custom js method to print something more meaningful to the page.
here's a basic implementation based on the register route handler:
var register = function(){
$(".page").html("");
// use the getText ajax function to get the page content:
getText('partials/register.php', function(content) {
$(".page").html(content);
var script = document.createElement('script');
script.src = "js/register.js";
$(".page").append(script);
});
};
/******************************************
* Ajax helpers
******************************************/
// Issue a Http GET request for the contents of the specified Url.
// when the response arrives successfully, verify it's plain text
// and if so, pass it to the specified callback function
function getText(url, callback) {
var request = new XMLHttpRequest();
request.open("GET", url);
request.onreadystatechange = function() {
// if the request is complete and was successful -
if (request.readyState === 4 && request.status === 200) {
// check the content type:
var type = request.getResponseHeader("Content-Type");
if (type.match(/^text/)) {
callback(request.responseText);
}
}
};
// send it:
request.send(null); // nothing to send on GET requests.
}
I find this a good way to 'module-ize' my code into partial views and separated JavaScript files that can be swapped in/out of the page easily.
I will be working on a way to make this more dynamic and even cache these 'modules' for repeated use in an SPA scenario.
I'm relatively new to web dev so if you can see any problems with this or a safer/better way to do it I'm all ears :)
Yes you can load Javascript from a dynamic page, but not with load() as load strips any Javascript and inserts the raw HTML.
Solution: pull down raw page with a get and reattach any Javascript blocks.
Apologies that this is in Typescript, but you should get the idea (if anything, strongly-typed TypeScript is easier to read than plain Javascript):
_loadIntoPanel(panel: JQuery, url: string, callback?: { (): void; })
{
// Regular expression to match <script>...</script> block
var re = /<script\b[^>]*>([\s\S]*?)<\/script>/gm;
var scripts: string = "";
var match;
// Do an async AJAX get
$.ajax({
url: url,
type: "get",
success: function (data: string, status: string, xhr)
{
while (match = re.exec(data))
{
if (match[1] != "")
{
// TODO: Any extra work here to eliminate existing scripts from being inserted
scripts += match[0];
}
}
// Replace the contents of the panel
//panel.html(data);
// If you only want part of the loaded view (assuming it is not a partial view)
// using something like
panel.html($(data).find('#product-content'));
// Add the scripts - will evaluate immediately - beware of any onload code
panel.append(scripts);
if (callback) { callback(); }
},
error: function (xhr, status, error)
{
alert(error);
}
});
}
Plain JQuery/Javascript version with hooks:
It will go something like:
var _loadFormIntoPanel = function (panel, url, callback) {
var that = this;
var re = /<script\b[^>]*>([\s\S]*?)<\/script>/gm;
var scripts = "";
var match;
$.ajax({
url: url,
type: "get",
success: function (data, status, xhr) {
while(match = re.exec(data)) {
if(match[1] != "") {
// TODO: Any extra work here to eliminate existing scripts from being inserted
scripts += match[0];
}
}
panel.html(data);
panel.append(scripts);
if(callback) {
callback();
}
},
error: function (xhr, status, error) {
alert(error);
}
});
};
$(".product-slot a").live('click', function() {
var myUrl = $(this).attr("href") + " #product-content";
_loadFormIntoPanel($("#product-overlay-inner"), myUrl, function() {
// Now do extra stuff to loaded panel here
});
$("#product-overlay").fadeIn();
return false;
});
I am trying to make a tinymce type editor. I want it to be extendable with plugins just like tinymce is. My question is how I could go about loading and using external javascript files in my plugin?
You could create a new script tag to pull in the javascript file:
YourEditor.loadPlugin = function(url) {
var scriptElement = document.createElement('script');
scriptElement.src = url;
document.body.appendChild(scriptElement);
};
If the loaded javascript was wrapped in a call to register itself with your editor:
YourEditor.registerPlugin("some-plugin", function(YourEditor) {
/* plugin code */
});
In your core code you would declare a function:
YourEditor.registerPlugin = function(name, loadFunction) {
loadFunction (this);
// fire an event (dummy syntax)
this.fire('pluginLoaded', name);
};
Then you could fire an event out of YourEditor to let the user of the editor know that the plugin 'some-plugin' has been loaded.
Registering the plugins works in a similar manner to jsonp in that it let's you load code from an arbitrary origin based on knowledge of a shared function. It passed a name and a function to call that will set up everything the plugin needs to operate.
Here is what I decided to do:
Use the jQuery.getScript() function. Didn't even know it existed.
So here's my code:
loadplugins: function() {
var self = this;
var settings = self.settings;
var plugins = settings.plugins.split(/[\s,]+/);
var thispath = settings.script_url;
$.each(plugins, function(i,e) {
// add .js to the plugin and the path before it
var thisPlugin = thispath + settings.plugin_dir + e + '.js'; // I'll change this to work with a script or directory
$.getScript(thisPlugin, function(data, textStatus, jqxhr) {
console.log(data, textStatus, jqxhr);
self.registerPlugin(data, function() {
});
});
});
return true;
},
I'm having trouble reading this xml with jQuery.
http://jsfiddle.net/VLtqY/2/
XML:
<myElements type="AA" coID="A923">
<element1>01</element1>
<element2>02</element2>
<element3>03</element3>
</myElements>
I'm looking for the following output:
element1=01
element2=02
element3=03
A little help please.
First, you need to wrap your xml variable in a call to the jQuery function, as in $(xml). Then, a call to children() will get all of your target elements.
Here's a very basic (and sloppy), working example of iterating through the elements, but it's just the selector that needs changing:
var xml = '<myElements type="AA" coID="A923"><element1>01</element1> <element2>02</element2><element3>03</element3></typeData>';
var myOutput = $("#output");
myOutput.append("=== start ===<br />");
$(xml).children().each(function () {
var xmlnode = $(this);
myOutput.append(this.tagName + xmlnode.text() + '<br/>');
});
myOutput.append("=== end ===");
Working demo: http://jsfiddle.net/UByfW/2/
Try this
$('*', xml).each(function () {
replacing the the line
$(xml).find("myElements").each(function () {
or
$(xml).children().each(function () {
The reason is self-explanatory: you must fetch the children, not the root element.
You can use the jQuery parseXML (see docs) function to parse the string of XML into an XML document object. Just add this line somewhere between the variable declaration and your each loop:
xml = $.parseXML(xml);
The rest of it should work fine then. You can see an example here.
I would really suggest ajax for this. IE hates the way jquery grabs the xml.I have been using this for a very long time with lots of success and no problems.
$.ajax({
url: "path-to-file.xml",
dataType: ($.browser.msie) ? "text" : "xml",
success: function(data){
var xml;
if (typeof data == "string") {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
} else {
xml = data;
}
alert($(xml).find('element1').text());
alert($(xml).find('element2').text());
alert($(xml).find('element3').text());
},//END SUCCSESS
error: function(){
alert("Sorry, There was an error loading this information. Refresh the page or try again later. ");
history.go(-1);
}
});//END AJAX CALL
I know this looks like a lot, but it really isn't that bad. Put your path to your xml, in the .each() do what you want to do.