"));
Livro - ASP.NET AJAX In Action Debug JavaScript no Visual Studio 2008 Book - ASP.NET AJAX In Action Debug JavaScript in Visual Studio 2008
Out 01 Oct 01

image Este posting vai ser especialmente grande! This posting will be especially great! Pois o Visual Studio 2008 está cheio de novidades relacionada com o desenvolvimento de JavaScript. Because Visual Studio 2008 is full of news related to the development of JavaScript.

A principal novidade, muito esperada nos últimos tempos, é o intellisense para JavaScript, que vem tornar a sua programação muito mais natural, proporcionando ao desenvolvedor um ambiente menos propício a erros, e um desenvolvimento muito mais rápido. The main novelty, much awaited in recent times, is the IntelliSense for JavaScript, which is making its programming more natural, allowing the developer to an environment less conducive to errors, and a development much faster.


Desde há algum tempo atrás que se tem tentado implementar esta funcionalidade, o problema é que o JavaScript é uma linguagem não tipada, ou seja, até a variável ser inicializada com o valor o seu tipo é desconhecido, pois pode ser qualquer. For some time ago that has tried to implement this feature, the problem is that JavaScript is a language not tipada, until the variable is initialized with the value of their type is unknown, it can be any. Para contornar este problema, o intellisense usa inferência, adaptando-se ao tipo que as variáveis assumem no código. To circumvent this problem, the USA IntelliSense inference, adapting to the type that takes the variables in the code. Nos exemplos seguintes vão ficar a perceber melhor este conceito. In the following examples will be to better understand this concept.

Vamos começar por criar um novo website no Visual Studio 2008, para a framework 3.5. Let's start by creating a new website in Visual Studio 2008, to 3.5 framework. Nesse site vamos criar uma página com uma calculador simples em javascript. In this site we will create a page with a simple calculator in javascript. Começamos por criar uma função “sum”, que vai somar dois números. We started by creating a function "sum", which will add two numbers. Ao começarmos a escrever function, o intellisense é-nos logo apresentado. To begin to write function, the IntelliSense is submitted to us soon.

image

Para percebermos melhor o funcionamento do intellisense por inferência, vamos criar uma variável de teste e instânciá-la com uma string. To better understand the operation of the IntelliSense by inference, we will create an instance variable and test it with a string.

image

Como podemos ver pela imagem anterior, o intellisense analisou a variável e como esta estava instânciada como string, só apresenta as opções para variáveis desse tipo. As we can see the previous image, the IntelliSense examined as a variable and this was instantiated as string, only presents the options for such variables. Se agora atribuirmos um “int” à variável, o intellisense vai adaptar-se e só mostrar as opções para “ints”. If we give a "int" to the variable, the IntelliSense will adapt and just show the options for "Ints.

image

Voltando ao exemplo da calculadora, vamos criar a função que vai receber dois números, vai somá-los. Returning to the example of the calculator, we will create a function that will receive two numbers, will Soma-los. Como esta função poderá ser necessária noutras páginas, vamos criá-la num ficheiro JavaScript à parte. As this may be necessary in other pages, we create it in a JavaScript file to the party.

image

Como vamos utilizar esta função fora do ficheiro, é melhor que a mesma esteja documentada, para sabermos qual a sua finalidade quando a mesma aparece no intellisense. How we use this function outside of the file, it is better that it is documented, to know what their purpose when it appears in the IntelliSense. Esta situação está prevista pelo Visual Studio 2008, e só temos de documentar a função utilizando um formato semelhante ao usado no ASP.NET. This is provided by Visual Studio 2008, and we just have to document the function using a format similar to that used in ASP.NET. Noutro post irei dar mais detalhes sobre este formato. In another post I will give more details on this format.

Vamos então documentar a função: We will then document the basis of:

image

Como podemos ver pela imagem anterior, podemos definir um resumo da função (summary), o tipo de parâmetros que a função recebe, e qual o resultado que é devolvido. As we can see the previous image, we can define a summary of the function (summary), the type of parameters that the function takes, and what the result is returned. Estes comentários poderão depois ser extraídos, gerando um documento com toda a documentação. These comments can then be extracted, generating a document with all the documentation.

Agora que já temos a função criada, vamos construir o interface da aplicação, adicionando duas textboxs, um span e um botão à nossa página aspx. Now that we have created the function, we will build the interface of the application, adding two textboxs, a span and a button on our aspx page.

image

Necessitamos também de adicionar uma referência ao ficheiro JavaScript onde criámos a função, bastando arrastá-lo da Solution Explorer para cima do design, sendo automaticamente criada a referência para o mesmo. We also need to add a reference to the file where we set up a JavaScript function, simply drag it from the Solution Explorer up the design, the reference is automatically created for it.

image

Na nossa página vamos chamar a função acabada de criar, para somar os valores introduzidos nas textboxs. In our page we call the newly created role, to add the values entered in textboxs.

image

Como é visível na imagem anterior, o intellisense apresenta-nos a função criada, bem como o resumo que adicionamos na documentação da mesma. As is visible in the picture above, the IntelliSense displays created us to function and the summary added that the documentation of it. Na introdução dos parâmetros, o intellisense mostra-nos também o que cada parâmetro deve receber. In the introduction of parameters, the IntelliSense shows us what each parameter should receive.

image

Depois da soma, vamos mostrar o resultado no span “txtResult” criado anteriormente, para isso, vamos usar o novo comando “$get” introduzido pelo ASP.NET AJAX. After the sum, we show the result in the span "txtResult" created earlier for this, we will use the new command "$ get" introduced by ASP.NET AJAX. Este comando permite obter um elemento do DOM, de forma semelhante ao document.getElementByID, mas sem a necessidade de nos preocuparmos com compatibilidades do browser. This gives a command element of the DOM, similar to document.getElementById, but without the need to concern ourselves with the browser compatibility. Também para estes comando temos o intellisense. Also we have the command for these IntelliSense.

image

A página deverá neste momento conter o código seguinte: The page will now contain the following code:

< body > <Body>

< form id =”form1″ runat =”server”> <Form id = "Form1" runat = "server">

< div > <Div>

< asp : ScriptManager ID =”ScriptManager1″ runat =”server”> <Asp: ScriptManager ID = "ScriptManager1" runat = "server">

</ asp : ScriptManager > </ Asp: ScriptManager>

< script language =”javascript” type =”text/javascript”> <Script language = "javascript" type = "text / javascript">

function sum(number1, number2) function sum (number1, number2)

{ (

var result = soma(parseInt(number1), parseInt(number2)); var result = sum (parseInt (number1), parseInt (number2));

$get( “txtResult” ).innerHTML = result; $ get ( "txtResult"). innerHTML = result;

} )

</ script > </ Script>

</ div > </ Div>

< div > <Div>

< input type =”text” id =”txtNumb1″ /> <Input type = "text" id = "txtNumb1" />

< input type =”text” id =”txtNumb2″ /> <Input type = "text" id = "txtNumb2" />

= < span id =”txtResult” style =” width : 100px ; “> = <Span id = "txtResult" style = "width: 100px;"> </ span > </ Span>

< input type =”button” id =”btnOk” onclick =”javascript:sum($get(’txtNumb1′).value, $get(’txtNumb2′).value);” <Input type = "button" id = "btnOk" onclick = "javascript: sum ($ get ( 'txtNumb1'). Value, $ get ( 'txtNumb2'). Value);"

value =”Somar” /> value = "Add" />

</ div > </ Div>

</ form > </ Form>

</ body > </ Body>

Podem testar a página e verificar que conseguem efectuar somas correctamente, sem refrescamento da página, apenas com JavaScript. Can test and verify that the page can make money properly, without refresh the page, only with JavaScript.

O Visual Studio 2008 tem ainda um excelente suporte para a criação de bibliotecas JavaScript. Visual Studio 2008 still has a great support for the creation of JavaScript libraries. Vamos supor que queremos criar outro ficheiro JavaScript onde vamos necessitar da função “soma” do ficheiro JScript.js. Let's assume that we want to create another file where we need the JavaScript function "sum" of the file JScript.js. Para termos intellisense das funções existentes no ficheiro criado anteriormente, necessitamos de referenciá-lo no novo. IntelliSense in terms of functions in the file created earlier, we need to reference it in again. Como podem ver na imagem seguinte, basta uma pequena linha de código, para que o Visual Studio 2008 nos disponibilize o intellisense para as funções do outro ficheiro. As you can see in the next image, just a small line of code, so that Visual Studio provides the IntelliSense in 2008 for the functions of other file.

image

Com esta funcionalidade o desenvolvimento de JavaScript estruturado em vários ficheiros torna-se bastante mais simples, usando estes comentários “reference”. With this feature the development of JavaScript structured in multiple files becomes much simpler, using these comments "reference". Podemos até referenciar a biblioteca do ASP.NET AJAX para termos acesso às novas funções disponibilizadas. We can even refer to the ASP.NET AJAX library to have access to new features available.

image

O Visual Studio 2008 possui também intellisense para os novos webservices que são disponibilizados através da plataforma ASP.NET AJAX. Visual Studio 2008 also includes IntelliSense for new webservices that are available through the ASP.NET AJAX platform. Estes webservices podem depois ser consumidos através de JavaScript nas páginas. Webservices These can then be consumed by JavaScript on pages. O intellisense do Visual Studio 2008 reconhece as funções destes webservices e mostra-as, para que seja mais fácil a sua invocação. The IntelliSense Visual Studio 2008 recognizes the role of webservices and shows them to be easier to your point.

Para testarmos, podemos criar um novo WebService no site, com a seguinte função: To test, we can create a new Web site in with the following function:

image

Descomentando a linha [System.Web.Script.Services.ScriptService], para que este webservice possa ser utilizado pelo ASP.NET AJAX (JavaScript). Uncommenting the line [System.Web.Script.Services.ScriptService], for this webservice can be used by ASP.NET AJAX (JavaScript).

Depois no ScriptManager referenciamos este WebService. After ScriptManager referenced in this Web.

image

Assim que executarmos este passo, passamos a ter as funções do WebService disponíveis no intellisense. Once you implement this step, we have the functions available on the Web IntelliSense.

image

Como puderam ver através deste extenso artigo, o intellisense de JavaScript do Visual Studio 2008 sofreu melhoramentos muito grandes, tornando o desenvolvimento de JavaScript muito mais fácil e agradável. How could see through this extensive article, the JavaScript IntelliSense in Visual Studio 2008 has very great improvements, making the development of JavaScript much easier and enjoyable.

O debug do JavaScript será abordado noutro artigo, pois este já está demasiadamente grande. The debug the JavaScript will be addressed in another article, because it is already too large.

Se tiverem dúvidas deixem um comentário. If you have questions leave a comment. :)


publicado por NC Etiquetas: 13 , 86 published by NC Etiquetas: 13, 86

2 Responses a “Suporte JavaScript e AJAX do Visual Studio 2008” 2 Responses to "JavaScript and AJAX Support in Visual Studio 2008"

  1. Novidades do Visual Studio 2008 « Isto Mesmo Diz: What's New in Visual Studio 2008 "Even That Says:

    [...] » Suporte para JavaScript e AJAX [...] [...] "Support for JavaScript and AJAX [...]

  2. domelhor.net Diz: domelhor.net Says:

    Suporte JavaScript e AJAX do Visual Studio 2008 JavaScript and AJAX support in Visual Studio 2008

Deixar uma resposta Leave a Reply