Loading "knockout.mapping" plugin using require.js - asp.net-mvc-3

I am creating an MVC3 application, with requireJS. In my views I need to convert the Model object into a knockout viewmodel object. So I need to use knockout and knockout.mapping libraries.
My application is designed in the following way,
1). All the script files are categorized into folders
Scripts/app/home/ - contains the scripts for the views in Home controller.
Scripts/lib/ - contains the scripts like jQuery, knockout,knockout.mapping, requirejs etc
2). In the "_Layout.cshtml" I am referencing "require.js" like this.
<script src="#Url.Content("~/Scripts/lib/require.js")" type="text/javascript"></script>
3). To configure the require.js settings I am using a different script file called "common.js" (Scripts/lib/common.js)
require.config(
{
baseUrl: "/Scripts/",
paths:{
jquery: "lib/jquery-2.0.3",
ko: "lib/knockout-2.3.0",
komapping: "lib/knockout.mapping"
}
});
4). This is my index.js file which is in 'Scripts/app/home/"
define(['ko', 'komapping'], function (ko, komapping) {
var person = function () {
var self = this;
self.getPersonViewModel = function (data) {
return ko.mapping.fromJS(data); ;
};
};
return { Person: person };
});
5). This is my "Index" action method in the "Home" controller
public ActionResult Index()
{
var person = new Person
{
Id = 1,
Name = "John",
Addresses = new List<Address>(new[]{new Address{Country = "Country 1", City = "City 1"}})
};
return View(person);
}
6). Finally this is my "Index" view
#model MMS.Web.Models.Person
<script type="text/javascript">
require(["/Scripts/common/common.js"], function () {
require(["app/home/index"], function (indexJS) {
var person = new indexJS.Person();
var vm = person.getPersonViewModel(#Html.Raw(Json.Encode(Model)));
});
});
</script>
The problem which I am facing is when loading the index.js file, I get a script error that the knockout.js cannot be loaded.
Failed to load resource: the server responded with a status of 404 (Not Found) - http:///Scripts/knockout.js
But if I remove the dependency of "komapping" inside the "index.js" file it loads correctly, but then I cannot use the mapping functionality.
I had a look inside these links, but couldn't find a solution,
Knockout.js mapping plugin with require.js and
https://github.com/SteveSanderson/knockout.mapping/issues/57
Your help, suggestions are much appreciated. Thanks!

I had the same issue. The problem is that the knockout.mapping defines a knockout dependency, so you need to satisfy this one when you load the script.
Here is how you should load your mapping stuff
require.config(
{
baseUrl: "/Scripts/",
paths:{
jquery: "lib/jquery-2.0.3",
knockout: "lib/knockout-2.3.0",
komapping: "lib/knockout.mapping"
},
shim: {
komapping: {
deps: ['knockout'],
exports: 'komapping'
}
}
});
Then in my case, I use an index.js file with a requirejs call like the following
requirejs(['jquery', 'knockout', 'komapping'], function($, ko, komapping){
ko.mapping = komapping;
//Do other stuff here
});

Related

How to add live search function into Laravel

I have Japan postal zip code live search function. It works at my xampp. I tried to add this into Laravel app but the search doesn't work.
Here is my whole code which works at XAMPP.
https://jsfiddle.net/blueink/rnsftzg8/
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="//jpostal-1006.appspot.com/jquery.jpostal.js"></script>
<script type="text/javascript">
$(window).ready( function() {
$('#postcode').jpostal({
postcode : [
'#postcode1'
],
address : {
'#address1' : '%3',
'#address2' : '%4',
'#address3' : '%5',
'#address1_kana' : '%8',
'#address2_kana' : '%9',
'#address3_kana' : '%10'
},
trigger : {
'#address1_kana' : true,
'#address2_kana' : true,
'#address3_kana' : false
}
});
$("#address1_kana").on("change", function() {
var val = $("#address1_kana").val();
val = "onchange_" + val;
$("#address1_kana_onchange").val(val);
});
$("#address2_kana").on("change", function() {
var val = $("#address2_kana").val();
val = "onchange_" + val;
$("#address2_kana_onchange").val(val);
});
$("#address3_kana").on("change", function() {
var val = $("#address3_kana").val();
val = "onchange_" + val;
$("#address3_kana_onchange").val(val);
});
});
</script>
What I tried is ...
First I save all js into public/js folder but it didn't work. So
I simple save js file app.blade.php which is header.
Then I save html code into index.blade.php.
I'm wondering why it works at xampp only?
Could you teach me what I missing please?
You can do it like so (depending on your Laravel version, mine is 5.7) :
First, create a route in the "routes" folder like this :
Route::get('test', 'TestController#test')->name('test');
You will be able to access to this road in the /test URL.
In your TestController.php file (usually in app/Http/Controllers), create a method :
public function test(){
return view('test');
}
Then, in resources/views, create a file named test.blade.php
In this file, put the HTML part of this fiddle:
https://jsfiddle.net/dayLkp4s/
After that, you can split header, footer, scripts parts in other files to use them elsewhere.
Useful resources
https://laravel.com/docs/5.7/blade

Kendo-UI components when using Durandaljs

I'm spent days trying to work out how to use the kendo-ui component with Durandal but to no avail.
I've managed to add a kendo-ui component declaratively on the page i.e. . This has no problems.
However, I would like to do some animations based on page events. Coding directly in the javascript viewmodel makes it easier to manipulate afterwards.
I've added my code below (which doesn't work), and I'm not sure that I'm taking the right approach. Actually, I'm sure I'm not. Anyone who can point me in the right direction I would appreciate it.
Any help or suggestions are welcome
Main.js
requirejs.config({
paths: {
'text': '../lib/require/text',
'durandal':'../lib/durandal/js',
'plugins': '../lib/durandal/js/plugins',
'transitions' : '../lib/durandal/js/transitions',
'jquery': '../lib/jquery/jquery-1.9.1',
'kendo': '../lib/kendo/kendo.ui.core.min',
'knockout': '../lib/knockout/knockout-3.1.0',
'bootstrap': '../lib/bootstrap/js/bootstrap',
'toastr': '../lib/toastr/toastr',
'lib': '../lib'
},
shim: {
'kendo': { deps: ['jquery'], exports: 'kendo' },
'bootstrap': {deps: ['jquery'],exports: 'jQuery'}
}
});
define(['durandal/system', 'durandal/app', 'durandal/viewLocator', 'durandal/binder', 'kendo'], function (system, app, viewLocator, binder, kendo) {
app.title = 'My Jumpstart';
//specify which plugins to install and their configuration
app.configurePlugins({
router:true,
dialog: true,
widget: {
kinds: ['expander']
}
});
kendo.ns = "kendo-";
binder.binding = function (obj, view) {
kendo.bind(view, obj.viewModel || obj);
};
app.start().then(function () {
viewLocator.useConvention();
app.setRoot('shell');
});
});
index.js
define(['durandal/app', 'durandal/system', 'knockout', 'toastr', 'kendo'],
function (app, system, ko, toastr, kendo) {
var myButton = function () {
var kbutton = $("#myButton").kendoButton();
};
var vm = {
myButton: myButton
};
return vm;
});
index.html
<section>
<div id="myButton">My Kendo Button</div>
</section>
Instead of shimming, add the Kendo libraries via the <script> tag on your index.html page. Be sure to add it after jQuery.
Also, are you using the knockout-kendo library from Ryan Niemeyer? That would affect my answer.

jsrender external templates not getting rendered

I have a MVC project. I am new to jsrender and try to render it.
I have a js file which contains all the jquery function. so i have put my template in there as well. The code for that looks like:-
function doSomething(){
var movies = [
{ name: "The Red Violin", releaseYear: "1998" },
{ name: "Eyes Wide Shut", releaseYear: "1999" },
{ name: "The Inheritance", releaseYear: "1976" }
];
$.when($.get('../Views/Hr/Templates/_mytemplates.tmpl.html'))
.done(function (tmplData) {
alert(tmplData);
$.templates({ tmpl: tmplData });
$('#divload').html(
$.render.tmpl(movies)
);
});
}
The js file is located in the Scripts/myScripts folder.
I am not able to render this template.
Can anybody explain why i am having the issue?
Thanks in advance

Load JavaScript when partial is called via ColorBox?

It seems when loading a Razor partial view via ColorBox (not using an iframe), the JavaScript libraries do not initialize properly or it is an artifacte of the partial. If I include the libraries in the parent page, the JavaScript function runs inside the partial jsut fine. I don't see any errors coming from the browser when the library is in the partial, but it is not working. If I move the library (in this case fileuploader.js) outside of the partial and keep the function in the partial it works fine.
Example:
<script src="#Url.ContentArea("~/Scripts/plugins/ajaxUpload/fileuploader.js")" type="text/javascript"></script>
<div id="file-uploader">
<noscript>
<p>
Please enable JavaScript to use file uploader.</p>
</noscript>
</div>
<script>
$(function () {
var fileCount = 0;
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: '/Admin/Avatar/AvatarUpload',
debug: true,
params: {
'userId': '#ViewBag.UserId'
},
onSubmit: function (id, fileName) {
fileCount++;
},
onComplete: function (id, fileName, responseJson) {
if (responseJson.success) {
if (createAvatar(responseJson.file, responseJson.imageId)) {
fileCount--;
} else {
fileCount--;
}
} else {
$("span.qq-upload-file:contains(" + fileName + ")").text(responseJson.errorMessage);
fileCount--;
}
if (fileCount == 0) {
.....
}
},
onCancel: function (id, fileName) {
fileCount--;
if (fileCount == 0) {
....
}
}
});
});
<script>
You may want to check whether there are duplicate references to the JavaScript libraries you are using (one in the parent and one in the partial).
This is a common issue and it will not raise any errors whatsoever, but will stop your JavaScript code from executing.
I think this is a time line problem.Before the "Partial View" load(or appending the div) JavaScript try to bind it and fail.So it cannot find a element which is in your Partial View document.I had a problem with like this with "ColorBox".I have found a solution for this problem.For example : When you call GET or POST method ,after the query put a control point like this .For example for binding "colorbox" :
function getMyPartial(partialname) {
var resultDiv = document.getElementById("content");
$.ajax({
type: "GET",
url: partialname,
async: false,
success: function (data) {
resultDiv.innerHTML = "";
resultDiv.innerHTML = data.toString();
}
});
var indd = 0; //This is Control Point
if (partialname == "YourPartialName") {
var yourelementinpartial= document.getElementById("example");
while (!yourelementinpartial) {
indd++;
}
$(".group4").colorbox({ rel: 'group4' }); //binding point
}
}
At the control point, if any of the element in your PartialView document has found it will bind.

Ajax Upload using valums ajax upload plugin inside a form

i just came across this ajax upload plugin and i wish to use it inside a form as shown in the demo page example 3. For some reason i am not able to make it work. I am not sure what parameters come into the function. For example here is my sample code.
$(document).ready(function(){
var upload = new AjaxUpload('property_i',
{
action: 'submitproperty.php',
autoSubmit: false,
onSubmit : function(file , extension){
return false;
}
});
var upload_data = upload.setData({
'propertytype':'propertytype'
});
});
Now the ID used in the AjaxUpload function should be ID of the or of the Entire form. Also how do i use setData method. Any suggestions or links will be very helpful. Thanks
I got it to work with the following code:
new AjaxUpload('#uploader_button', {
action: 'filename.ashx',
autoSubmit: true,
onSubmit: function(file, ext) {
// --- stuff here
// --- add postdata parameters
this.setData({ id: 1, title: docTitle.val() });
},
onComplete: function(file, response) {
// --- stuff here too
}
});
it doesn't utilize the var but instead adds the custom data params in the onSubmit block. The only other difference is that I haven't wrapped the parameter key in quotes as it seems to serialize correctly. And I'm not using autoSubmit: false , but instead it's true...
The only way I could get this to work with autoSubmit: false is to add this outside any function:
var uploader;
var uploadFile;
then in the AjaxUpload(...
onChange: function(file, response){
uploader = this;
uploadFile = file;
},
then in the function to do the upload:
uploader.setData({session: session});
uploader.submit();
Hope this helps
I'm using uploadify and very useful.
http://www.uploadify.com/

Resources